Source: gradient.js

const _canvas_height = 512;
const _canvas_width = 1024;
var myStippling;

/**
 * Initialize the gradient image which will later be stippled and perform the stippling iterations until there is no
 * more splitting or deleting
 */
function initGradient() {

    createCanvas();
    var d3canvas = d3.select("canvas");
    var context = d3canvas.node().getContext('2d');

    var imageData = context.getImageData(0, 0, _canvas_width, _canvas_height);
    myStippling = new Stippling(_canvas_height, _canvas_width, 5000, 100, true, imageData.data);

    var state = [1, 1];

    while (state[0] !== 0 && state[1] !== 0) {
        state = myStippling.iterate();
        myStippling.drawStipples();
    }
}

/**
 * Create a canvas on which the image to be stippled is added
 */
function createCanvas() {
    var canvas = d3.select('#container')
        .append('canvas')
        .attr('width', _canvas_width)
        .attr('height', _canvas_height);

    var ctx = canvas.node().getContext("2d");

    // Create gradient
    var grd = ctx.createLinearGradient(0, 0, _canvas_width, 0);
    grd.addColorStop(0, "black");
    grd.addColorStop(1, "white");

// Fill with gradient
    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, _canvas_width, _canvas_height);
}

function nextStep() {
    myStippling.iterate();
    myStippling.drawStipples();
}