00 Votes

HTML5 Canvas: 1 px Line creates 2 Pixel Line with wrong Color

Question by PC Control | 2014-05-20 at 23:45

I really like the possibilities, the HTML 5 canvas element is offering! However, up to now, I have not succeeded in drawing a simple one pixel width line on my canvas.

I am using the following code:

var canvas = document.getElementById('canv');
var context = canvas.getContext('2d');

context.beginPath();
context.moveTo(0, 10);
context.lineTo(100, 10);
context.strokeStyle = "#000000";
context.lineWidth = 1;
context.stroke();

Although I have explicitly specified, that the line should have a width of exactly one pixel, a 2-pixel-line is drawn instead. Also the color, I have determined, only seems to be faded and not as specified.

Funnily, it is all working well when specifying another value for lineWidth. For example, I can draw a 2px line without any problems. What can I do?

ReplyPositiveNegativeDateVotes
1Best Answer1 Vote

The phenomenon you are describing is resulting from the fact that a line is always drawn on half of a pixel. If you correct your code by this half pixel, your line should be drawn normally:

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

When drawing on a smooth coordinate, the line is set exactly between two pixels. The result is that the line extends over the two adjacent pixels with reduced color intensity.

Of course, this problem only arises when drawing horizontal or vertical lines. Therefore, I have only set the 10 from your example to 10.5 (x-axis) and I have not changed the 0 and 100 from the y-axis.
2014-05-21 at 16:37

ReplyPositive Negative
00 Votes

In addition, you can also use the function translate() to change the general behavior:

context.translate(0.5, 0.5);

By using translate(), the coordinate system of the canvas is moved by the determined values. This means, with using translate(0.5, 0.5) the point 0/0 is moved to 0.5/0.5.

Or with other words: When starting line at 1/1, after this translate, the point would automatically be 1.5/1.5 instead - the values 0.5/0.5 are simply added to each coordinate and this makes the lines always starting at a smooth position.

Important: Calling translate() is reseted for example with changing the size of the canvas.
2014-05-22 at 16:21

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.