canvas实现虚线带箭头效果

在这里插入图片描述

<canvas id="canvas"/>
// startX, startY:起点坐标
// finalX, finalY:终点坐标 
// theta:三角斜边与直线夹角
// headlen:三角斜边长度
// width:箭头线宽度
// color:箭头颜色
const   getArrow=( startX, startY, finalX, finalY,theta=30,headlen=10,width=1,color="#000")=>{
  var idName = document.getElementById("canvas");
  var ctx = idName.getContext("2d");

  // 计算各角度和对应坐标
  var angle = Math.atan2(startY - finalY, startX - finalX) * 180 / Math.PI,
      angle1 = (angle + theta) * Math.PI / 180,
      angle2 = (angle - theta) * Math.PI / 180,
      topX = headlen * Math.cos(angle1),
      topY = headlen * Math.sin(angle1),
      botX = headlen * Math.cos(angle2),
      botY = headlen * Math.sin(angle2);
  ctx.save();
  var arrowX ,arrowY ;
  //绘制箭头
  ctx.beginPath();
  arrowX = finalX + topX;
  arrowY = finalY + topY;

  ctx.moveTo(arrowX, arrowY);
  ctx.lineTo(finalX, finalY);
  arrowX = finalX + botX;
  arrowY = finalY + botY;
  ctx.lineTo(arrowX, arrowY);
  ctx.strokeStyle = color;
  ctx.lineWidth = width;

  ctx.stroke();
  ctx.closePath();
  arrowX = startX - topX;
  arrowY = startY - topY;
  //绘制虚线
  ctx.beginPath();

  ctx.setLineDash([28, 8]);//实线 去掉此句

  ctx.moveTo(arrowX, arrowY);
  ctx.moveTo(startX, startY);
  ctx.lineTo(finalX, finalY);
  ctx.stroke();
  ctx.restore();
  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值