关于javascript:学习笔记Canvas适配高清屏

33次阅读

共计 676 个字符,预计需要花费 2 分钟才能阅读完成。

有个 window 属性叫 devicePixelRatio,能够算出过后设施的物理像素与 CSS 像素的比率。
语法:

value = window.devicePixelRatio;

用法:

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

    canvas.width = 600
    canvas.height = 400

    canvas.style.width = canvas.width + 'px'
    canvas.style.height = canvas.height + 'px'
    canvas.width = canvas.width * dpr
    canvas.height = canvas.height * dpr
    
    ctx.scale(dpr, dpr);
    ctx.rect(20, 30, 400, 200)
    ctx.fillStyle = "purple"
    ctx.fillRect(20, 30, 400, 300)
    
    ctx.font = '28px Arial'
    ctx.fillStyle = '#fff'
    ctx.fillText('ABCD', 100,150)
    ctx.strokeStyle = '#fff'
    ctx.strokeText('YES',100,180)
    
  </script>

正文完
 0