Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Really weird canvas behavior with putImageData

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

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

HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading