Drawing lines in canvas, but the last ones are faded

后端 未结 3 1266
时光取名叫无心
时光取名叫无心 2020-11-30 14:31

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 ha

相关标签:
3条回答
  • 2020-11-30 15:08

    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.

    0 讨论(0)
  • 2020-11-30 15:09

    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.

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题