Skip to content

Instantly share code, notes, and snippets.

@ooflorent
Last active February 18, 2024 21:19
Show Gist options
  • Save ooflorent/fc05f8981e37e90b6c92615383c90e6d to your computer and use it in GitHub Desktop.
Save ooflorent/fc05f8981e37e90b6c92615383c90e6d to your computer and use it in GitHub Desktop.
Canvas helpers & noise generator
/**
* @param {number} width
* @param {number} height
* @param {!CanvasPattern} pattern
* @constructor
*/
function Texture(width, height, pattern) {
this.width = width
this.height = height
this.pattern = pattern
}
/**
* Creates a HTML canvas.
* @param {number} width
* @param {number} height
* @return {!HTMLCanvasElement}
*/
function createCanvas(width, height) {
let canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
return canvas
}
/**
* Draws a texture into a canvas patterns.
* @param {number} width
* @param {number} height
* @param {boolean} repeat
* @param {function(!CanvasRenderingContext2D)} draw
* @return {!Texture}
*/
function createTexture(width, height, repeat, draw) {
let canvas = createCanvas(width, height)
let ctx = canvas.getContext("2d")
draw(ctx)
let pattern = ctx.createPattern(canvas, repeat ? "repeat" : "no-repeat")
return new Texture(width, height, pattern)
}
/**
* Generates a noise texture.
* @param {number} width
* @param {number} height
* @param {number} intensity
* @return {!Texture}
*/
function createNoise(width, height, intensity) {
return createTexture(width, height, true, ctx => {
let pixels = ctx.createImageData(width, height)
let noise = new Uint8Array(width * height)
crypto.getRandomValues(noise)
for (let i = 0; i < pixels.data.length; i += 4) {
pixels.data[i + 3] = noise[i >> 2] * intensity
}
ctx.putImageData(pixels, 0, 0)
})
}
export {
createCanvas,
createTexture,
createNoise,
}
import {createCanvas, createNoise} from "./canvas"
const GAME_WIDTH = 800
const GAME_HEIGHT = 600
// The number of noise patterns to generate.
// Increment this to add more randomness.
const NOISE_PATTERNS = 20
// Creates the game canvas
let canvas = createCanvas(GAME_WIDTH, GAME_HEIGHT)
let ctx = canvas.getContext("2d")
// Generates noise patterns
let noises = []
for (let i = 0; i < NOISE_PATTERNS; ++i) {
noises.push(createNoise(200, 200, 0.2))
// ^^^ ^^^ ^^^
// the pattern size ──┴────┘ │
// │
// change this value to control
// the noise opacity
}
function update() {
// Clears the screen
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT)
// - Run the game logic
// - Draw the world
// …
// Finally draw the noise. Noise pattern could also be generated here
// for more visual randomness.
// Picks a random noise pattern
let noise = noises[(Math.random() * NOISE_PATTERNS) | 0]
// Draws it
ctx.fillStyle = noise.pattern
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment