在画布中绘制线条,但最后的线条已褪色 [英] Drawing lines in canvas, but the last ones are faded

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

问题描述

我正在尝试在黑色背景上绘制一个由白线组成的网格.

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.

参见插图:第一条水平线是在 y 位置为 1 的情况下绘制的.这条线模糊且宽.第二条水平线的 y 位置为 4.5.它既薄又精确.

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/

在所有像素上绘制一条线这一事实意味着绘制一条宽度恰好为一个像素的水平线的唯一方法是瞄准中间.我通常在基于画布的应用程序中使用这种 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆