Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - Drawing lines in canvas, but the last ones are faded

I'm trying to draw a grid of white lines on a black background.

The bottom 3 horizontal lines seem faded until I redraw them, and I can't figure out why this is happening. Has anyone seen this before and/or know what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is due to the fact lines are drawn over all pixels they're over (on canvas positionning is in float). When you want to draw precise vertical or horizontal lines in javascript on a canvas, you'd better have them in half ints.

See illustration : The first horizontal line was drawn with a y position of 1. This line is fuzzy and wide. The second horizontal line was drawn with a y position of 4.5. It is thin and precise.

enter image description here

For example in your code, I had good results by changing your horizontal lines loop to this :

                // Horizontal lines
                for (var i = 1; i < objCanvas.height / intGridWidth; i++)
                {
                    objContext.strokeStyle = "white";
                    var y = Math.floor(i*intGridWidth)+0.5
                    objContext.moveTo(0, y);
                    objContext.lineTo(objCanvas.width, y);
                    objContext.stroke();
                }

Here's a fiddle demonstrating it with very thin and clean lines :

http://jsfiddle.net/dystroy/7NJ6w/

The fact that a line is drawn over all pixels it is over means the only way to draw an horizontal line with a width of exactly one pixel is to target the middle. I usually have this kind of util functions in my canvas based applications :

function drawThinHorizontalLine(c, x1, x2, y) {
    c.lineWidth = 1;
    var adaptedY = Math.floor(y)+0.5;
    c.beginPath();
    c.moveTo(x1, adaptedY);
    c.lineTo(x2, adaptedY);
    c.stroke();
}

Of course you'd better do it for vertical lines too to have a good looking page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...