• 使用 canvas 画图时图像文字模糊的解决办法


    最近在使用 canvas 画图的时候,遇到了图像文字模糊的问题,解决思路就是根据分辨率创建不同尺寸的画布。以下是创建高分辨率画布的代码:

    /**
     * 创建高分辨率画布
     * @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-polyfill

  • 相关阅读:
    错因集锦
    组合数学12
    硬币购物
    考试套路整理
    考前模板整理
    我的友链
    P4127 [AHOI2009]同类分布
    P1836 数页码_NOI导刊2011提高(04)
    P4124 [CQOI2016]手机号码
    数位DP小结
  • 原文地址:https://www.cnblogs.com/nzbin/p/9447882.html
Copyright © 2020-2023  润新知