4

有个window属性叫devicePixelRatio,可以算出当时设备的物理像素与CSS像素的比例。
语法:

value = window.devicePixelRatio;

然后将canvas按倍数绘制,再用CSS进行缩放,则达到高清的效果。
用法:

    /** @type {HTMLCanvasElement} */
    let canvas = document.getElementById("canvas")
    let ctx = canvas.getContext('2d')
    let dpr = window.devicePixelRatio || window.webkitDevicePixelRatio || window.mozDevicePixelRatio || 1;

    let originalWidth = 600, 
        originalHeight = 400

    canvas.style.width =  `${originalWidth}px`
    canvas.style.height = `${originalHeight}px`
    canvas.width = originalWidth * dpr
    canvas.height = originalHeight * dpr

    ctx.scale(dpr, dpr);
    ctx.rect(20, 30, 400, 200)
    ctx.fillStyle = "#000"
    ctx.fillRect(20, 30, 400, 300)
    
    ctx.font = '28px Arial'
    ctx.fillStyle = '#fff'
    ctx.fillText('Hello World', 30,150)
    ctx.strokeStyle = '#fff'
    ctx.strokeText('Hello World',30,180)
    
    let img  = new Image()
    img.onload = function(){
      ctx.drawImage(img, 200, 100, 400, 250)
    }
    img.src = "https://jianxiujiucan.github.io/demo/img/05.jpg"
  </script>

剑锈酒残
195 声望4 粉丝

我已忘了江湖原来的模样。