Drawing lines in canvas, but the last ones are faded

筅森魡賤 提交于 2019-12-17 07:51:09

问题


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?


回答1:


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.

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.




回答2:


It doesn't look faded for me. Maybe it's something to do with your OS or PC, which is not able to render the drawing properly. I'm using Chrome 20 on Win 7. Test it out.




回答3:


You have to define objContext.lineWidth like this:

objContext.lineWidth = 2;

I'm not sure why last line gets faded though. See http://jsfiddle.net/jSCCY/



来源:https://stackoverflow.com/questions/10373695/drawing-lines-in-canvas-but-the-last-ones-are-faded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!