Skip to content

Instantly share code, notes, and snippets.

@domoritz
Last active October 5, 2021 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domoritz/b5b46eb71f8dbf22e4d18593611fe71c to your computer and use it in GitHub Desktop.
Save domoritz/b5b46eb71f8dbf22e4d18593611fe71c to your computer and use it in GitHub Desktop.
Fast Canvas Shifting
license: bsd-3-clause
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fast scrolling heatmap</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d", {
desynchronized: true
});
const width = window.innerWidth;
const height = window.innerHeight;
ctx.imageSmoothingEnabled = false;
console.log("Canvas Size", width, height);
ctx.canvas.width = width;
ctx.canvas.height = height;
const imgData = ctx.getImageData(0, 0, 1, height);
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function redraw() {
requestAnimationFrame(() => {
draw();
redraw();
});
}
function draw() {
for (let j = 0; j < imgData.data.length; j += 4) {
imgData.data[j] = randomInt(0, 255); // red
imgData.data[j + 1] = randomInt(0, 255); // green
imgData.data[j + 2] = randomInt(0, 255); // blue
imgData.data[j + 3] = 255; // alpha
}
ctx.putImageData(imgData, width - 1, 0);
ctx.globalCompositeOperation = "copy";
ctx.drawImage(ctx.canvas, -1, 0);
ctx.globalCompositeOperation = "source-over";
}
redraw();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment