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

Hoa*_*Hoa 7 javascript canvas

我在这里有一个例子

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();
Run Code Online (Sandbox Code Playgroud)

我所做的是保存上下文,更改线宽,绘制线,然后恢复上下文.但是所有线的厚度都是相同的.我究竟做错了什么?

小智 9

您需要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();
Run Code Online (Sandbox Code Playgroud)

如果你不使用,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();
Run Code Online (Sandbox Code Playgroud)

如果只调整一个或两个参数,则不需要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();
}
Run Code Online (Sandbox Code Playgroud)

用法:

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');
Run Code Online (Sandbox Code Playgroud)

纠正小提琴:http:
//jsfiddle.net/AbdiasSoftware/8NzjH/4/

重新排列版本:http:
//jsfiddle.net/AbdiasSoftware/8NzjH/5/