While following the MDN canvas tutorial, I encountered an issue with a code snippet I wrote. The code is supposed to color the top left corner (50x50 pixels) of the canvas in red.
However, I'm receiving an error message that says Overload resolution failed
and I haven't been able to find a solution through Google searches.
Test002.html:35 Uncaught TypeError: Failed to execute 'putImageData' on 'CanvasRenderingContext2D': Overload resolution failed.
at draw (Test002.html:35:8)
draw @ Test002.html:35
load (async)
(anonymous) @ Test002.html:48
This issue occurred in my testing with Chrome. I'm not quite sure where I went wrong... Any thoughts or suggestions?
<html>
<body>
<canvas id="canvas1" width="800" height="600" style="border: 1px solid black;">
<script type="text/javascript">
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
console.log(idata);
const getColorIndicesForCoord = (x, y, width) => {
const red = y * (width * 4) + x * 4;
return [red, red + 1, red + 2, red + 3];
};
const colorIndices = getColorIndicesForCoord(5, 5, canvas.width);
const [redIndex, greenIndex, blueIndex, alphaIndex] = colorIndices;
function draw() {
console.log("Started drawing.");
for (let i=0; i<50; i++) {
for (let j=0; j<50; j++) {
putPixel(i, j, 200, 0, 0);
}
}
// (imageData, xLoc, yLoc, 0, 0, imgWidth, imgHeight);
ctx.putImageData(idata, 0, 0, 0, 0);
console.log("Finished drawing.");
}
function putPixel(x,y,r,g,b) {
let colorIndices = getColorIndicesForCoord(x, y, canvas.width);
idata[colorIndices[0]] = r;
idata[colorIndices[1]] = g;
idata[colorIndices[2]] = b;
// idata[colorIndices[3]] = a;
}
window.addEventListener("load", draw);
</script>
</body>
</html>