How to draw arrow on canvas tag with JavaScript?

Sometimes, we want to draw arrow on canvas tag with JavaScript.

In this article, we’ll look at how to draw arrow on canvas tag with JavaScript.

How to draw arrow on canvas tag with JavaScript?

To draw arrow on canvas tag with JavaScript, we use the moveTo and lineTo methods.

For instance, we write

const canvasArrow = (context, fromx, fromy, tox, toy) => {
  const headlen = 10;
  const dx = tox - fromx;
  const dy = toy - fromy;
  const angle = Math.atan2(dy, dx);
  context.moveTo(fromx, fromy);
  context.lineTo(tox, toy);
  context.lineTo(
    tox - headlen * Math.cos(angle - Math.PI / 6),
    toy - headlen * Math.sin(angle - Math.PI / 6)
  );
  context.moveTo(tox, toy);
  context.lineTo(
    tox - headlen * Math.cos(angle + Math.PI / 6),
    toy - headlen * Math.sin(angle + Math.PI / 6)
  );
};

const ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
canvasArrow(ctx, 10, 30, 200, 150);
ctx.stroke();

to call moveTo to move to the starting point iun the canvasArrow function.

Then we call lineTo to draw to the next points.

Finally, we call stroke to finishing drawing.

Conclusion

To draw arrow on canvas tag with JavaScript, we use the moveTo and lineTo methods.