在画布上绘制线条

在画布上绘制线条

本文介绍了在画布上绘制线条,但最后一条线条褪色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在黑色背景上绘制白线的网格。

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

底部的3条水平线似乎褪色,直到我重画它们,找出为什么会发生这种情况。有没有人看过这个和/或知道我做错了什么?

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?

推荐答案

在它们结束的所有像素上(在画布上的位置是浮动的)。当你想在画布上的javascript中绘制精确的垂直或水平线时,最好将它们设置为半角。

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.

查看插图:绘制第一条水平线其中ay位置为1.这条线是模糊和宽的。第二水平线用4.5的y位置绘制。

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 :

在所有像素上绘制一条线的事实意味着绘制一条宽度恰好为一个像素的水平线的唯一方法是将中间。我通常在我的基于canvas的应用程序中有这样的util函数:

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.

这篇关于在画布上绘制线条,但最后一条线条褪色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:36