JSFiddle - React, Tailwind, and code Playground
by antelopelovefan
HTML
<canvas id="canvas" width="320" height="240">
<p>Your browser doesn't support canvas.</p>
</canvas>
CSS
canvas { background: #000; }
JavaScript
if(typeof console=='undefined')console={log:function(){}};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var clear = function() { canvas.width = canvas.width; };
Object.prototype.setPixel = function(point, rgba) {
if(!this.hasOwnProperty('data')) {
throw'This method only works with ImageData objects created with createImageData';
}
var imageData = this;
if(typeof rgba == 'string') {
var useDefault = true; //If anything is wrong with the hex code, fall back to a default color
var matches;
//We were passed a string so let's see if it's a valid hex code
if(rgba.length == 7) {
//Full length hex code (eg #AABBCC)
matches = rgba.toLowerCase().match(/#([abcdef0-9]{2})([abcdef0-9]{2})([abcdef0-9]{2})/);
}else if(rgba.length == 4) {
//Short hex code (eg #ABC)
matches = [
'',
rgba[1]+rgba[1],
rgba[2]+rgba[2],
rgba[3]+rgba[3]
];
}
if(matches.length == 4) {
rgba = [];
for(var i=1;i<=3;i++) {
rgba.push(parseInt(matches[i],16));
}
rgba.push(255); //Add the alpha
useDefault = false;
}
if(useDefault) {
rgba = [255,255,255,255];
}
}
if(rgba.length <= 3 ) { rgba.push(255); } //Add alpha if not provided
i = (point.x + point.y * imageData.width) * 4;
console.log('Drawing at ' + point.x + ',' + point.y);
imageData.data[i ] = rgba[0]; //r
imageData.data[i+1] = rgba[1]; //g
imageData.data[i+2] = rgba[2]; //b
imageData.data[i+3] = rgba[3]; //a
};
var rnd = function(maxRange) {
return Math.floor(Math.random()*maxRange);
};
var midpoint = function(p1, p2) {
return {x:Math.round((p1.x+p2.x)/2),...