如何在HTML画布中改变线条的粗细?

14

这里有一个例子:

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();

我所做的是保存场景,更改线条宽度,画线,然后恢复场景。但是所有线的粗细都相同。我做错了什么?

2个回答

20

对于每条线,您需要使用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();

如果您只是调整一个或两个参数,并且保持跟踪它们(例如在这里我们每次都设置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/


0

我正在尝试绘制如下的粗中线: - Wex
不太对,我希望只有中间那个变粗。我尝试更新了你的代码,但现在前两个都变粗了。http://jsfiddle.net/8NzjH/3/ - Hoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接