Canvas drawing arrows

Canvas of  CanvasRenderingContext2D the object is not to provide a method to draw an arrow, that is, if we need to draw an arrow in the Canvas is the need to deal with their own wrapper function.

Package function

// ctx:Canvas绘图环境
// fromX, fromY:起点坐标(也可以换成 p1 ,只不过它是一个数组)
// toX, toY:终点坐标 (也可以换成 p2 ,只不过它是一个数组)
// theta:三角斜边一直线夹角
// headlen:三角斜边长度
// width:箭头线宽度
// color:箭头颜色
function drawArrow(ctx, fromX, fromY, toX, toY,theta = 30,headlen = 10,width = 1,color = '#333') {
    var theta = theta || 30,
        headlen = headlen || 10,
        width = width || 1,
        color = color || '#000',
        angle = Math.atan2(fromY - toY, fromX - toX) * 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();
    ctx.beginPath();
    var arrowX, arrowY;
    ctx.moveTo(fromX, fromY);
    ctx.lineTo(toX, toY);
    arrowX = toX + topX;
    arrowY = toY + topY;
    ctx.moveTo(arrowX, arrowY);
    ctx.lineTo(toX, toY);
    arrowX = toX + botX;
    arrowY = toY + botY;
    ctx.lineTo(arrowX, arrowY);
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
    ctx.restore();
}

Call it

var canvas = document.querySelector('#mycanvas');
var ctx = canvas.getContext('2d');
drawArrow(ctx, 150, 100, 350,100);

Renderings:

Double-headed arrow:

function drawArrow(ctx, fromX, fromY, toX, toY,theta,headlen,width,color) {
  var theta = theta || 30,
      headlen = headlen || 10,
      width = width || 1,
      color = color || '#000',
      angle = Math.atan2(fromY - toY, fromX - toX) * 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();
  ctx.beginPath();
  var arrowX = fromX - topX,
      arrowY = fromY - topY;
  ctx.moveTo(arrowX, arrowY);
  ctx.lineTo(fromX, fromY);
  arrowX = fromX - botX;
  arrowY = fromY - botY;
  ctx.lineTo(arrowX, arrowY);
  ctx.moveTo(fromX, fromY);
  ctx.lineTo(toX, toY);
  // Reverse length on the other side
  arrowX = toX + topX;
  arrowY = toY + topY;
  ctx.moveTo(arrowX, arrowY);
  ctx.lineTo(toX, toY);
  arrowX = toX + botX;
  arrowY = toY + botY;
  ctx.lineTo(arrowX, arrowY);
  ctx.strokeStyle = color;
  ctx.lineWidth = width;
  ctx.stroke();
  ctx.restore();
}

 

Published 94 original articles · won praise 29 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_41849462/article/details/103861714