Inconsistency between Chrome and Firefox with scripted alteration of css on a canvas

14 hours ago 1
ARTICLE AD BOX

I was running into a problem with a canvas-based game I am developing, and I created a minimal reproduction of the issue here:

addEventListener("load", () => { const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.fillRect(0, 0, canvas.width, canvas.height); setTimeout(() => { ctx.clearRect(0, 0, canvas.width, canvas.height); canvas.style.backgroundImage = "url('https://picsum.photos/id/723/650/200')"; }, 500); }); canvas { background-size: 100% 100%; background-color: black; } <canvas height="180" width="610"></canvas>

On Firefox, the behavior displayed is that which I intended. When the page loads, the canvas is turned red, and then, half a second later, the image test.png is loaded as the CSS background.

On MS Edge, and on Chrome, the behavior is different. After the 500 milliseconds, the canvas turns black, with no image displayed. The canvas's state is somewhat unstable though. If you go into the inspect element menu and perform these steps, the image is finally shown:

Uncheck the background-color property on the canvas element from the <style> block

Uncheck the background-image property in the style attribute that was added by the javascript

Re-check background-image property

This behavior is very unexpected. I would like to understand why this is happening, and need to know how to make the behavior consistent (make Edge/Chrome act like Firefox currently does).

Read Entire Article