I am trying to draw a vertical arrow using canvas and javascript. i am able to draw one with arrow head upwards but finding difficulty in placing arrow head at the bottom.
The code i am trying
<!DOCTYPE html>
<html>
<body>
<canvas id="c" width="500" height="500" style="border:1px solid grey"></canvas>
<script>
const ctx = document.getElementById("c").getContext("2d");
drawArrow(ctx, 300, 300, 300, 200);
function drawArrow(context, fromx, fromy, tox, toy) {
const headlen = 10; // length of head in pixels
const angle = Math.atan2(toy - fromy, tox - fromx);
context.beginPath();
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));
context.stroke();
}
</script>
</body>
</html>
which is drawing a an arrow like this
What i need is the same arrow head which will be placed at the bottom downwards.
2
Answers
The arrow generation is already dynamic in the code you’ve found. All you need to do is change the coordinates of the start and end position.
Change
To
Here’s a working example:
The args just need to be switched around, because you are passing origin x, origin y, destination x, destination y. The X args stay the same, but y just needs to have an origin less than the destination: