Skip to content

Instantly share code, notes, and snippets.

@quickredfox
Forked from donpark/perlincanvas.js
Created December 9, 2012 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quickredfox/4246229 to your computer and use it in GitHub Desktop.
Save quickredfox/4246229 to your computer and use it in GitHub Desktop.
Rendering Perlin Noise Fast to HTML5 Canvas
/* Following canvas-based Perlin generation code originates from
* iron_wallaby's code at: http://www.ozoneasylum.com/30982
*/
function randomNoise(canvas, x, y, width, height, alpha) {
x = x || 0;
y = y || 0;
width = width || canvas.width;
height = height || canvas.height;
alpha = alpha || 255;
var g = canvas.getContext("2d"),
imageData = g.getImageData(x, y, width, height),
random = Math.random,
pixels = imageData.data,
n = pixels.length,
i = 0;
while (i < n) {
pixels[i++] = pixels[i++] = pixels[i++] = (random() * 256) | 0;
pixels[i++] = alpha;
}
g.putImageData(imageData, x, y);
return canvas;
}
function perlinNoise(canvas, noise) {
noise = noise || randomNoise(createCanvas(canvas.width, canvas.height));
var g = canvas.getContext("2d");
g.save();
/* Scale random iterations onto the canvas to generate Perlin noise. */
for (var size = 4; size <= noise.width; size *= 2) {
var x = (Math.random() * (noise.width - size)) | 0,
y = (Math.random() * (noise.height - size)) | 0;
g.globalAlpha = 4 / size;
g.drawImage(noise, x, y, size, size, 0, 0, canvas.width, canvas.height);
}
g.restore();
return canvas;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment