简体   繁体   中英

How to draw a single device pixel in a canvas

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:

  1. Create a canvas with the real size you want in physical pixels using the width and height attributes.
  2. Using CSS, set the canvas size to the real size divided by devicePixelRatio in CSS pixels (for both dimensions) using the width and height CSS properties.
  3. Draw to the canvas.

 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.

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