1. 模糊问题

dpr (devicePxielRatio)大于1的屏幕上,绘制图形将被放大,导致模糊。

根据dpr缩放canvas:  

TIP

这个示例在dpr大于1的屏幕上对比明显,dpr=1时,画布尺寸不做调整,看不出差异。

  • 关键代码
function setupCanvas(canvas) {
    // Get the device pixel ratio, falling back to 1.
    var dpr = window.devicePixelRatio || 1;
    // Get the size of the canvas in CSS pixels.
    var rect = canvas.getBoundingClientRect();
    // Give the canvas pixel dimensions of their CSS
    // size * the device pixel ratio.
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    var ctx = canvas.getContext('2d');
    // Scale all drawing operations by the dpr, so you
    // don't have to worry about the difference.
    ctx.scale(dpr, dpr);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

2. 一像素问题

上例中,在dpr=1的屏幕上显示,细心观察会发现,左侧矩形框的宽度并不是1像素(实际上为2像素)。这和canvas渲染原理有关,参考这里。解决方法是将绘制点调整+/-0.5像素。

调整0.5像素:  
根据dpr缩放canvas:  
  • 关键代码
if(this.onePixel === "yes") {
    // this.ctx.rect(160.5, 80.5, 150, 50); // 方法一
    this.ctx.translate(0.5, 0.5); // 方法二
    this.ctx.rect(160, 80, 150, 50);
} else {
    this.ctx.rect(160, 80, 150, 50);
}
1
2
3
4
5
6
7

参考

上次更新: 12/18/2018, 5:46:56 PM