JSFiddle - React, Tailwind, and code Playground
HTML
<title>canvas tutorial</title>
<body>
<canvas id="myCanvas" width="400" height="425"></canvas>
<script src="engine.js"></script>
</body>
JavaScript
var canvas = document.getElementById("myCanvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
// That's how you define the value of a pixel //
function drawPixel (x, y, r, g, b, a) {
var index = (x + y * canvasWidth) * 4;
canvasData.data[index + 0] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
}
// That's how you update the canvas, so that your //
// modification are taken in consideration //
function updateCanvas() {
ctx.putImageData(canvasData, 0, 0);
}
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
function sleep(ms) {
ms += new Date().getTime();
while (new Date() < ms){
}
}
console.log(1);
var color = new Object();
for (i = 0; i < 50; i++) {
for (j = 0; j < 50; j++) {
color.red = getRandom(1,255);
color.green = getRandom(1,255);
color.blue = getRandom(1,255);
setTimeout(function(i,j, red, green, blue){
drawPixel(i, j, red, green, blue, 255);
updateCanvas();
}, 100*i + 2*j + 2, i, j, color.red, color.green, color.blue)
}
}