使用 canvas 畫圖時圖像文字模糊的解決辦法

最近在使用 canvas 畫圖的時候,遇到了圖像文字模糊的問題,解決思路就是根據分辨率建立不一樣尺寸的畫布。如下是建立高分辨率畫布的代碼:git

/**
 * 建立高分辨率畫布
 * @param w     畫布寬
 * @param h     畫布高
 * @param ratio 屏幕分辨率
 */
function createHiDPICanvas(w, h, ratio?) {

  const PIXEL_RATIO = (function () {
    const c = <HTMLCanvasElement>document.createElement("canvas"),
      ctx = c.getContext("2d"),
      dpr = window.devicePixelRatio || 1,
      bsr = ctx['webkitBackingStorePixelRatio'] ||
        ctx['mozBackingStorePixelRatio'] ||
        ctx['msBackingStorePixelRatio'] ||
        ctx['oBackingStorePixelRatio'] ||
        ctx['backingStorePixelRatio'] || 1;

    return dpr / bsr;
  })();

  if (!ratio) { ratio = PIXEL_RATIO; }
  const can = document.createElement("canvas");
  can.width = w * ratio;
  can.height = h * ratio;
  can.style.width = w + "px";
  can.style.height = h + "px";
  can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
  return can;
}

// 不建立高分辨率畫布
const canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;

// 建立使用默認分辨率的畫布
const myCanvas = this.createHiDPICanvas(100, 100);

// 建立分辨率爲 3 的畫布
const myCustomCanvas = this.createHiDPICanvas(100, 100, 3);

最後,貼一個高分辨率畫布的開源庫
https://github.com/jondavidjohn/hidpi-canvas-polyfillgithub

相關文章
相關標籤/搜索