Adapted from Perlin Noise via Observable
- I replaced the
require("noise")
with asmartdown.importScriptUrl
call to async load the library. - I explicitly create the
<canvas>
element, rather than using theDOM
package that appears to be part of Observable. - Use
window.innerWidth
andwindow.innerHeight
instead of Observable's implicitwidth
.
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;
});