使用 for 循环在画布上绘制线条

cta*_*mli 6 javascript canvas

我正在尝试用画布绘制线条,并且正在使用 for 循环更改坐标。

这是我的画布元素:

<canvas id="c" width="300px" height="300px"></canvas>
Run Code Online (Sandbox Code Playgroud)

这是js代码:

var c = document.getElementById('c');
ci = c.getContext('2d');
for(var a = 18; a < 300; a +=18){
            fnc(a, ci);
            }   
function fnc(x, ci){

        ci.strokeStyle = 'red'; 
        ci.moveTo(0, x); 
        ci.lineTo(300, x); ci.lineWidth = 0.2; ci.stroke(); 
    }
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试绘制这些线条,它们之间有 18px 的间距。但是线条的粗细和颜色(或不透明度,我不确定)正在从上到下变化。

这是一个小提琴:http : //jsfiddle.net/J6zzD/1/

所以我找不到我的错误有什么问题。为什么颜色和粗细不一样?

更新 :

我只是从函数中写出这些线条,现在所有线条都变淡了,但粗细相同。这么奇怪 :

 ci.strokeStyle = 'red'; 
 ci.lineWidth = 0.2; ci.stroke();
Run Code Online (Sandbox Code Playgroud)

这是演示:http : //jsfiddle.net/J6zzD/4/

Gam*_*ist 6

这又是忘记调用 beginPath 的永恒问题。
\n每次调用 moveTo 和 lineTo 时,都会创建一个新的 *sub*path,该路径会添加到当前 Path 中。
\n然后每次调用Stroke()时,当前路径,因此当第一次绘制最后添加的路径时,所有当前子路径都会重新绘制。
\n由于不透明度会累加,因此绘制一次的底线将具有 20% 的不透明度 (lineWidth=0.2),而顶线将达到 100% 的不透明度 (alpha=255)。

\n\n

在第二个小提琴中,您仅描边一次,因此所有线条都有 20% 的不透明度,这对于 0.2 线宽来说是正确的。

\n\n

所以:在绘制新图形之前使用 beginPath。
\n在这种情况下,您有两种选择:
\n \xe2\x80\xa2 逐行绘制\n或
\n\xe2\x80\xa2 绘制一次将所有行作为子路径的路径。

\n\n

(参见下面的代码)。

\n\n

提示:要获得干净的线条,请记住像素的中心位于每个像素的 (+0.5, +0.5) 坐标,因此 \na \'trick\' 是在应用程序启动时平移 0.5, 0.5,然后仅使用圆角坐标和 lineWidth

\n\n

1)逐行绘制

\n\n

http://jsfiddle.net/gamealchemist/J6zzD/6/

\n\n
var c = document.getElementById(\'c\');\nvar ctx = c.getContext(\'2d\');\nctx.translate(0.5, 0.5);\nctx.lineWidth = 1;\n\nfor (var y = 18; y < 300; y += 18) {\n    strokeLine(ctx, y);\n}\n\nfunction strokeLine(ctx, y) {\n    ctx.beginPath();\n    ctx.strokeStyle = \'red\';\n    ctx.moveTo(0, y);\n    ctx.lineTo(300, y);\n    ctx.stroke();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

2) 绘制多个子路径:\n(一笔画只能有一种颜色() )

\n\n

http://jsfiddle.net/gamealchemist/J6zzD/7/

\n\n
var c = document.getElementById(\'c\');\nvar ctx = c.getContext(\'2d\');\nctx.translate(0.5, 0.5);\nctx.lineWidth = 1;\n\nctx.strokeStyle = \'red\';\n\nctx.beginPath();\nfor (var y = 18; y < 300; y += 18) {\n    addLineSubPath(ctx, y);\n}\nctx.stroke();\n\nfunction addLineSubPath(ctx, y) {\n    ctx.moveTo(0, y);\n    ctx.lineTo(300, y);\n}\n
Run Code Online (Sandbox Code Playgroud)\n