Ivan
Ivan

Reputation: 10372

How to get rid of feathered edges on HTML5 Canvas strokes?

Currently, when using the HTML5 canvas element, stroked paths have slightly feathered edges.

Here is some example code I am using:

this.context.lineJoin = "round";
this.context.lineTo(x1, y1);
this.context.lineTo(x2, y2);
this.context.closePath();
this.context.stroke();

I was wondering if there was a way to create lines without slightly feathered edges.

Upvotes: 2

Views: 422

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83348

Canvas uses subpixel accuracy.

Add 0.5 to your coorxinates. 0.0 is the border between pixels and thus line falls on two image data pixels.

Upvotes: 2

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

When drawing lines, canvas automatically antialiases them, which is what you describe as feathered edges.

To avoid antialiasing, you will need to draw the lines manually using putImageData directly. (see MDN for canvas pixel manipulation)

A suitable algorithm for this is Bresenham's line algorithm which is quite easy to implement for JS/canvas.

Upvotes: 2

Related Questions