1

I'm struggling to draw on HTML canvas using putImageData.

Here is my code: https://jsfiddle.net/173mbg0n/58/

HTML:

<canvas id='c'></canvas>

CSS:

canvas {
  width: 100px;
  height: 100px;
  background: red;
}

JavaScript:

let W = 100;
let H = 100;

let c = document.getElementById('c');
var ctx = c.getContext("2d");

let array = new Uint32Array(W * H);
for (let i = 0; i < array.length; i++)
   array[i] = 0xff00ffff;

let ca = new Uint8ClampedArray(array.buffer);
let img = new ImageData(ca, W);

ctx.putImageData(img, 0, 0);

Here is my result: https://i.stack.imgur.com/bzUxV.png

I expect all canvas to be yellow.

What I'm doing wrong?

1 Answers1

0

You have to give the <canvas> element height and width attributes:

<canvas id='c' height=100 width=100></canvas>

With that change, it works. The CSS sizing of the canvas determines how the canvas looks, while the attributes of the element determine it's geometry for drawing purposes.

Pointy
  • 405,095
  • 59
  • 585
  • 614