Search code examples
javascripthtmlcanvasfilterdrawing

Bad quality for 100% both width and height of canvas


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

http://jsfiddle.net/yPtr5/

<!DOCTYPE html>
<html>
    <head>
    <title></title>
    <style type="text/css">

    html, body {
        width: 100%;
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

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

    </style>
    </head>
    <body>
        <canvas id="myCanvas">
            Your browser does not support the HTML5 canvas tag.
        </canvas>
        <script>

            var canvas = document.getElementById( "myCanvas" );
            var context = canvas.getContext( "2d" );

            context.id = "myContext";
            context.beginPath();
            context.arc( 95, 50, 40, 0, 2 * Math.PI );
            context.stroke();

            setTimeout( function() { 
                var rectWidth = 150;
                var rectHeight = 75;
                context.fillStyle = "blue";
                context.fillRect( rectWidth / -2, rectHeight / -2, rectWidth, rectHeight );
            }, 2000 );

        </script> 
    </body>
</html>

As you are able to see, the rendering result has a very low quality:

enter image description here

So, I'm wondering, how can I draw various figures using Canvas in a good quality, I don't want to draw in small size, I want to draw in 100% size of page.

So, maybe I didn't define some anti aliasing filter or something else?

Thanks!


Solution

  • 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.