Canvas drawings, like lines, are blurry

I found that setting the canvas size in CSS caused my images to be displayed in a blurry manner.

Try this:

<canvas id="preview" width="640" height="260"></canvas>

as per my post: HTML Blurry Canvas Images


When drawing lines in canvas, you actually need to straddle the pixels. It was a bizarre choice in the API in my opinion, but easy to work with:

Instead of this:

context.moveTo(10, 0);
context.lineTo(10, 30);

Do this:

context.moveTo(10.5, 0);
context.lineTo(10.5, 30);

Dive into HTML5's canvas chapter talks about this nicely


Even easier fix is to just use this:

context = canvas.context2d;    
context.translate(0.5, 0.5);

From here on out your coordinates should be adjusted by that 0.5 pixel.


I use a retina display and I found a solution that worked for me here.

Small recap :

First you need to set the size of your canvas twice as large as you want it, for example :

canvas = document.getElementById('myCanvas');
canvas.width = 200;
canvas.height = 200;

Then using CSS you set it to the desired size :

canvas.style.width = "100px";
canvas.style.height = "100px";

And finally you scale the drawing context by 2 :

canvas.getContext('2d').scale(2,2);

The Mozilla website has example code for how to correct resolution in a canvas: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio

enter image description here

<!doctype html>
    <html lang="en">
    <head>
    <meta charset= "UTF-8">
    

    </head>
    
    <body>
        <div align = "center">
            <canvas id = "canvas">
    
            </canvas>
    
        </div>
          <script type="text/JavaScript">
            var canvas = document.getElementById('canvas');

            var ctx = canvas.getContext('2d');

            // Set display size (css pixels).
            var size = 200;
            canvas.style.width = size + "px";
            canvas.style.height = size + "px";

            // Set actual size in memory (scaled to account for extra pixel density).
            var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
            canvas.width = size * scale;
            canvas.height = size * scale;

            // Normalize coordinate system to use css pixels.
            ctx.scale(scale, scale);

            ctx.fillStyle = "#bada55";
            ctx.fillRect(10, 10, 300, 300);
            ctx.fillStyle = "#ffffff";
            ctx.font = '18px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';

            var x = size / 2;
            var y = size / 2;

            var textString = "I love MDN";
            ctx.fillText(textString, x, y);
      </script>
    </body>
    </html>