用鼠标绘图 c语言 改变线条的粗细,javascript – 如何在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、付费专栏及课程。

余额充值