您需要为每一行开始一个新路径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.save(); no need to do this
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(); //begin here
context.lineWidth = 2; //common width for the next two lines
context.moveTo(10, 10);
context.lineTo(50, 10);
context.moveTo(10, 50);
context.lineTo(50, 50);
context.stroke(); //stroke here to draw them
context.beginPath(); //start new path for new thickness
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
如果你只调整一个或两个参数,则不需要save()
/ restore()
context,只要你跟踪它们(就像我们在这里设置lineWidth
的那样。这在这种情况下更有效)。
可以选择只做一个函数,如:
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');
更正小提琴:http:
//jsfiddle.net/AbdiasSoftware/8NzjH/4/
重排版:http:
//jsfiddle.net/AbdiasSoftware/8NzjH/5/