zoukankan      html  css  js  c++  java
  • [Canvas] Make Canvas Responsive to Pixel Ratio

    Canvas is great for high performance graphics rendering but by default the results look blocky on phones tablets and laptops with high pixel density or Retina displays. By using canvas width and height attributes and style props we can use window.devicePixelRatio to create a canvas that is responsive to pixel ratio.

    It's much faster to paint graphics to the screen using canvas and DOM. But on high pixel density displays, like phones and Macbooks, the results look pixelated. This is because by default one canvas pixel equals one CSS pixel, not one screen pixel.

    To fix this, let's create a scale factor from the device pixel ratio. We use a scale factors to create a canvas, use width and height attributes, so double the CSS pixel width and height sizes we require. We make all our painting calls relative to the scale factor.

    const canvas = document.querySelector('canvas')
    const sf = window.devicePixelRatio
    const elWidth = canvas.width
    const elHeight = canvas.height
    canvas.width = elWidth * sf
    canvas.height = elHeight * sf
    const ctx = canvas.getContext('2d')
    ctx.arc(
      canvas.width / 2,
      canvas.height / 2,
      canvas.width / 2,
      0,
      Math.PI * 2
    )
    ctx.fill()
    canvas.style.width = `${elWidth}px`

    To recap, the width and height attributes on the canvas element determine the number of pixels in the canvas, while the CSS width and height properties determine the size it will display on the screen. By setting an element's attributes different to the CSS properties.

  • 相关阅读:
    获取windows所有用户名
    windbg内存查看(d*)
    Windbg查看调用堆栈(k*)
    Windbg调试互斥体(Mutex)死锁
    Windbg调试关键区(CriticalSection)死锁
    "R6002 floating point support not loaded"错误
    由可变参数引起的崩溃
    【Dubbo源码学习】负载均衡算法(2)-轮询算法的实现
    jdk1.8源码解析(1):HashMap源码解析
    Java annotation浅析
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5794207.html
Copyright © 2011-2022 走看看