简体   繁体   中英

Difference between “Coordinates in pixels” and “Coordinates” in Canvas HTML

I am working on video processing with JavaScript, I am doing fine, but I am using a method called, canvasCtx.rect (), it receives these parameters. 参数

And then I get to get the data from that rectangle that I drew with the getImageData () method, but it receives these parameters:

参数

They look similar and are almost the same, but in the "X" and "Y" coordinates, .rect () receives the coordinates and .getImageData () receives the "X" and "Y" coordinates as well, but now in pixels, and I do not know if it is my perception but I am drawing the data on a graph and I feel that they are a bit outdated, I wanted to know if in fact they must be different values ​​or it is really the same. Thank you.

Technically, only getImageData 's and putImageData 's parameters are in pixels, all other methods ones are relative to the current transformation matrix applied on your context.

For instance if you scale your context by 2, then drawing at 10, 10 will actually draw at 20px, 20px .

 const ctx = document.getElementById('canvas').getContext('2d'); // draw first with init matrix (coords 1,1 => 1px,1px) ctx.beginPath(); ctx.rect(10, 10, 50, 50); ctx.fillStyle = 'green'; ctx.fill(); // now draw scaled by 2 (coords 1,1 => 2px,2px) ctx.scale(2, 2); ctx.beginPath(); ctx.rect(10, 10, 50, 50); ctx.fillStyle = 'red'; ctx.fill();
 <canvas id="canvas"></canvas>

So it would be more correct to say that the parameters of rect() are in pixels multiplied by the current matrix , which is quite complex for an introduction, so whatever documentation you are reading would probably be better just to omit any unit, since there is actually none, just like MDN web docs 1 does.

Now getImageData and putImageData are not affected by the transform matrix, so these method's parameters could be said to be in pixel, since they will always map to one:

 const ctx = document.getElementById('canvas').getContext('2d'); // draw first with init matrix, coords 1,1 => 1px,1px ctx.beginPath(); ctx.rect(10, 10, 50, 50); ctx.fillStyle = 'green'; ctx.fill(); // scale by two ctx.scale(2, 2); const img = ctx.getImageData(10, 10, 50, 50); ctx.putImageData(img, 70, 10);
 <canvas id="canvas"></canvas>

1: I really advise you to start any research on a web API on this website from now on, they're not always entirely correct, but always link to the official specifications you can read, and in 99% of the cases, they'll offer a correct overview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM