JSFiddle - React, Tailwind, and code Playground
by brigand
HTML
<canvas id="test" width="512" height="512"></canvas>
CSS
canvas {
border: 1px solid red;
width: 95vw;
}
JavaScript
const MODE = false ? 'single' : 'double'; // change true->false
const canvas = document.querySelector('#test');
const canvasAlt = canvas.cloneNode(false);
var ctx = canvas.getContext("2d");
var ctxAlt = canvas.getContext("2d");
if (MODE === 'double') {
drawGradient(ctxAlt);
}
tick();
function drawGradient(ctx) {
const g = ctx.createLinearGradient(0, 0, 512, 0);
g.addColorStop(0, 'black');
g.addColorStop(1, "white");
ctx.fillStyle = g;
ctx.fillRect(0, 0, 512, 512);
}
function tick() {
if (MODE === 'single') {
drawGradient(ctx);
} else {
ctx.drawImage(canvasAlt, 0, 0, 512, 512);
}
ctx.fillStyle = 'red';
ctx.fillRect(Math.floor(Math.random() * (512 - 50)), 120, 50, 50);
requestAnimationFrame(tick);
}