Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas drawings, like lines, are blurry

Tags:

html

canvas

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);