在html中加上粗线,如何在HTML画布中改变我的线条粗细?

你需要用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');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值