Bad quality for 100% both width and height of canvas

后端 未结 2 1488
庸人自扰
庸人自扰 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:18

    The height and width need to be set on the height and width attributes of the canvas tag and not in CSS. Any CSS sizing of the canvas element merely stretches the canvas and does not size it properly.

    <canvas id="canvas" width="500px" height="500px">
    

    Have a look at this project that I posted on my site: Creating an HTML5 Paint App

    It includes a functionto resize the canvas when the browser window size changes (which you would have to modify):

            this.onScreenSizeChanged = function (forceResize) {
            if (forceResize || (this.canvas.width != window.innerWidth /*|| 
                                this.canvas.height != window.innerHeight*/)) {
    
                var image = this.context.getImageData(0, 0,
                        this.canvas.width, this.canvas.height);
    
                this.canvas.width = (window.innerWidth);
                this.canvas.height = (window.innerHeight);
    
                this.context.putImageData(image, 0, 0);
    
            }
        }
        this.onScreenSizeChanged(true);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题