Bad quality for 100% both width and height of canvas

后端 未结 2 1506
庸人自扰
庸人自扰 2021-01-15 07:37

I have done a very tiny example with canvas, it\'s available on JsFiddle:

http://jsfiddle.net/yPtr5/




        
2条回答
  •  难免孤独
    2021-01-15 08:31

    Problem

    In most general cases we should avoid using CSS to set the canvas size.

    The default size of canvas is 300 x 150 pixels (bitmap). If you set the size using CSS we'll just end up scaling those 300 x 150 pixels meaning the browser will start interpolating and smoothing the image, which is why you end up with a blurry result.

    Solution

    Remove these from the CSS-rule:

    #myCanvas {
      /*width: 100%;
      height: 100%;*/
      display: block;
      }
    

    and set the size in JavaScript like this:

    var canvas = document.getElementById( "myCanvas" );
    
    canvas.width = window.innerWidth;     // equals window dimension
    canvas.height = window.innerHeight;
    

    You can of course set any other size you need (in pixels). You probably want to define position (i.e. fixed or absolute) for the canvas' CSS as well if your goal is full window size.

    Hope this helps.

提交回复
热议问题