Skip to content

Instantly share code, notes, and snippets.

@DoctorBud
Last active February 1, 2018 04:04
Show Gist options
  • Save DoctorBud/9a7cbbe49ccaffbfd8cef2aa82f13cbe to your computer and use it in GitHub Desktop.
Save DoctorBud/9a7cbbe49ccaffbfd8cef2aa82f13cbe to your computer and use it in GitHub Desktop.
Perlin Noise

Mike Bostock's Perlin Noise Demo

Adapted from Perlin Noise via Observable

Required Changes

  • I replaced the require("noise") with a smartdown.importScriptUrl call to async load the library.
  • I explicitly create the <canvas> element, rather than using the DOM package that appears to be part of Observable.
  • Use window.innerWidth and window.innerHeight instead of Observable's implicit width.
var width = window.innerWidth;
var height = window.innerHeight;
var renderDiv = this.div;
renderDiv.style.width = width;
renderDiv.style.height = height;

this.div.innerHTML = `<canvas width="${width}" height="${height}" id="myCanvas"></canvas>`;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

var noiseLibraryURL = 'https://cdn.rawgit.com/josephg/noisejs/master/perlin.js';

smartdown.importScriptUrl(noiseLibraryURL, function(x) {
  noise.seed(Math.random());
  const image = context.createImageData(width, height);
  for (let y = 0, i = 0; y < height; ++y) {
    for (let x = 0; x < width; ++x, i += 4) {
      image.data[i + 3] = Math.abs(noise.perlin2(x / 100, y / 100)) * 256;
    }
  }
  context.putImageData(image, 0, 0);
  return context.canvas;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment