It seems really simple:
const ctx = document.getElementById("canvas").getContext("2d");
ctx.drawRect(x, y, 1, 1);
Unfortunately, in many devices this draws more than one pixel on the screen and sometimes a blurry blot. How can pixel-per-pixel control be achieved in an HTML5 <canvas>
?
The problem is that one CSS pixel is not defined as one pixel in the user's screen. In high PPI screens 1 CSS pixel ≠ 1 "real" pixel.
Fortunately, window.devicePixelRatio
contains the ratio between the length of 1 CSS pixel and 1 physical pixel. For example, a devicePixelRatio
of 2 means that 1 CSS pixel = 2 physical pixels.
Here's a solution:
width
and height
attributes.devicePixelRatio
in CSS pixels (for both dimensions) using the width
and height
CSS properties. const canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"); canvas.style.width = 200/devicePixelRatio + "px"; canvas.style.height = 100/devicePixelRatio + "px"; ctx.fillRect(2, 2, 1, 1);
<canvas id="canvas" width="200" height="100"></canvas>
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.