您需要为每行开始一个带有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()上下文,因为我们每次都设置了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');