I have been experimenting with a basic JavaScript snippet to showcase an unusual HTML5 canvas behavior I've encountered.
Every 100ms, I am drawing the same set of strokes but in a different sequence. Strangely, some of the strokes change color intermittently. This oddity occurs only when I shuffle the order of drawing between calls, even though the lines are consistently drawn in the same position and color each frame.
const canvasWidth = 500;
const gapBetweenLines = 5;
const nbrLines = canvasWidth / gapBetweenLines;
const canvasHeight = 500;
const canvas = document.getElementById('map');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// generate an array of line objects, each assigned a random color
let lines = [];
for (let i = 0; i < nbrLines; i++) {
lines.push({
index: i,
x: i * gapBetweenLines,
color: '#' + Math.floor(Math.random() * 16777215).toString(16)
});
}
// utility function to shuffle the given array
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// draw lines on the canvas periodically using random colors
function drawLines() {
const shuffledLines = [...lines];
shuffle(shuffledLines);
let ctx = canvas.getContext('2d');
for (let i = 0; i < nbrLines; i++) {
const line = shuffledLines[i];
ctx.strokeStyle = line.color;
// ctx.save();
ctx.beginPath();
ctx.moveTo(line.x, 0);
ctx.lineTo(line.x, canvasHeight);
ctx.stroke();
// ctx.restore();
}
}
// invoke the drawLines function every 100ms
setInterval(drawLines, 100);
<!DOCTYPE html>
<html>
<body>
<h1>Fluctuating Lines</h1>
<canvas id="map"></canvas>
<div id="lineinfo"></div>
</body>
</html>
In the last day, I've dedicated quite a bit of time trying to pinpoint the root cause of this issue. Is there something fundamental about HTML5 Canvas drawing that eludes me?
Interestingly, preserving and restoring the context between each stroke yields no discernible difference.