Skip to content

Instantly share code, notes, and snippets.

@donpark
Created February 11, 2012 04:45

Revisions

  1. donpark created this gist Feb 11, 2012.
    39 changes: 39 additions & 0 deletions perlincanvas.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    /* 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;
    }