JSFiddle - React, Tailwind, and code Playground
by Jon Eyrick
HTML
<div>Fast setPixel()</div>
<canvas id="test-canvas" width="256" height="256"></canvas>
JavaScript
// Convenience method for creating objects from prototype objects.
_ = function(prototype) {
var o = Object.create(prototype);
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
for (var key in arg) {
if (!o[key]) {
o[key] = arg[key];
}
}
}
if (o.constructor) {
o.constructor();
}
return o;
}
// Prototype object for canvas
Canvas = {};
Canvas.constructor = function() {
var canvas = document.getElementById(this.id);
this.context = canvas.getContext('2d');
this.width = canvas.width;
this.height = canvas.height;
this.context.fillRect(0, 0, this.width, this.height);
}
Canvas.beginPaint = function() {
this.imageData = this.context.getImageData(0, 0, this.width, this.height);
this.data = this.imageData.data;
}
Canvas.endPaint = function() {
this.context.putImageData(this.imageData, 0, 0);
}
// Fast setting of pixel
// x: the x-coordinate for the pixel
// y: the y-coordinate for the pixel
// r: the red value (0-255)
// g: the green value (0-255)
// b: the blue value (0-255)
Canvas.setPixel = function(x, y, r, g, b) {
var index = (x + this.width * y) * 4;
this.data[index] = r;
this.data[index + 1] = g;
this.data[index + 2] = b;
}
// Example - Set all pixels in test canvas
var canvas = _(Canvas, {id:'test-canvas'});
canvas.beginPaint();
for (var y = 0; y < canvas.height; y++) {
for (var x = 0; x < canvas.width; x++) {
canvas.setPixel(x, y, x, y, Math.floor((x * y) / 255));
}
}
canvas.endPaint();