Skip to content

Instantly share code, notes, and snippets.

@ptgamr
Forked from jwir3/canvasArrowhead.js
Created January 19, 2022 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptgamr/022d301f5e31303bd408874d38ca4be1 to your computer and use it in GitHub Desktop.
Save ptgamr/022d301f5e31303bd408874d38ca4be1 to your computer and use it in GitHub Desktop.
Code to create an arrowhead on an html5 canvas
/**
* Draw an arrowhead on a line on an HTML5 canvas.
*
* Based almost entirely off of http://stackoverflow.com/a/36805543/281460 with some modifications
* for readability and ease of use.
*
* @param context The drawing context on which to put the arrowhead.
* @param from A point, specified as an object with 'x' and 'y' properties, where the arrow starts
* (not the arrowhead, the arrow itself).
* @param to A point, specified as an object with 'x' and 'y' properties, where the arrow ends
* (not the arrowhead, the arrow itself).
* @param radius The radius of the arrowhead. This controls how "thick" the arrowhead looks.
*/
function drawArrowhead(context, from, to, radius) {
var x_center = to.x;
var y_center = to.y;
var angle;
var x;
var y;
context.beginPath();
angle = Math.atan2(to.y - from.y, to.x - from.x)
x = radius * Math.cos(angle) + x_center;
y = radius * Math.sin(angle) + y_center;
context.moveTo(x, y);
angle += (1.0/3.0) * (2 * Math.PI)
x = radius * Math.cos(angle) + x_center;
y = radius * Math.sin(angle) + y_center;
context.lineTo(x, y);
angle += (1.0/3.0) * (2 * Math.PI)
x = radius *Math.cos(angle) + x_center;
y = radius *Math.sin(angle) + y_center;
context.lineTo(x, y);
context.closePath();
context.fill();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment