11

我这里有一个例子

http://jsfiddle.net/8NzjH/

我正在尝试绘制一条粗中间线,如下所示:

var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.fillStyle = '#000000';

context.moveTo(10, 10);
context.lineTo(50, 10);

context.save();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.restore();

context.moveTo(10, 50);
context.lineTo(50, 50);

context.stroke();

我所做的是保存上下文,更改线宽,画线然后恢复上下文。然而,所有线条的粗细都是相同的。我究竟做错了什么?

4

2 回答 2

16

您需要为每一行开始一个新路径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/

于 2013-06-19T15:35:08.180 回答
0

它是否像预期的那样工作?

http://jsfiddle.net/8NzjH/1/

context.lineWidth = 15;
context.stroke();
于 2013-06-19T07:49:21.323 回答