对于每条线,您需要使用beginPath()
开始新路径,设置lineWidth
,然后使用stroke()
绘制每条线。
以下是一个调整示例(请参见下面的代码):
var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.beginPath();
context.moveTo(10, 10);
context.lineTo(50, 10);
context.lineWidth = 2;
context.stroke();
context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
context.beginPath();
context.moveTo(10, 50);
context.lineTo(50, 50);
context.lineWidth = 2;
context.stroke();
如果你不使用
beginPath()
,你将会重绘所有的线条,这会使整个过程变慢。如果所有的线条都有相同的粗细,你可以在一开始使用单个
beginPath()
。
你还可以重新排列代码,使具有相同粗细的线条在同一个路径下分组等。例如:
context.beginPath();
context.lineWidth = 2;
context.moveTo(10, 10);
context.lineTo(50, 10);
context.moveTo(10, 50);
context.lineTo(50, 50);
context.stroke();
context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
如果您只是调整一个或两个参数,并且保持跟踪它们(例如在这里我们每次都设置lineWidth
),则无需save()
/restore()
上下文。在这种情况下,这更有效率。
可选地,只需创建一个函数:
function drawLine(ctx, x1, y1, x2, y2, width, color) {
if (typeof width === 'number') ctx.lineWidth = width;
if (typeof color === 'string') ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
使用方法:
drawLine(context, 0, 0, 100, 100); //width and color is optional
drawLine(context, 0, 0, 100, 100, 10);
drawLine(context, 0, 0, 100, 100, 10, '#f00');
已更正的 JSFiddle:
http://jsfiddle.net/AbdiasSoftware/8NzjH/4/
重新排列的版本:
http://jsfiddle.net/AbdiasSoftware/8NzjH/5/