How to Draw Arrow Head Line using KineticJS?

KineticJS is a JavaScript Library which allow us to render high performance graphics over a HTML5 Canvas. Let us talk about an Application where we need to draw flowcharts & Lines. From one node to another node while drawing a line I want to show arrow head for the line. To make arrow head line dynamic it required few mathematical calculation. Look at the example below. Here I created line with arrow head.

In the sample application I have two points for the line. Which is declared as x1, y1 & x2, y2. lineArrowConfig holds configuration setting for arrow head line. To draw finally adding the line configuration to layer & using draw method rendering the stage.

To run the below application copy the codes into a notepad file & save it as a html file. Before run the html file make sure you are with Internet Connectivity. Because here I used CDN link to refer KineticJS library.

Demo App to Draw arrow Head Line

<!DOCTYPE html>
<html>
<head>
<title>Example to draw line with Arrow head using KineticJS</title>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.2.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
.kineticjs-content { background-color: lightblue; }
</style>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">

/* Declaration of Stage */
var stage = new Kinetic.Stage({
container: 'container',
width: 540,
height: 280,
draggable: false
});

/* Declartion of Layer */
var layer = new Kinetic.Layer({
name: 'layer'
});

/*Points for Line Draw*/
var x1 = 100;
var y1 = 100;
var x2 = 200;
var y2 = 200;

var headlen = 10;
var angle = Math.atan2(y2-y1,x2-x1);

/*Configuration settings for Line*/
var lineArrowConfig = new Kinetic.Line({
id: 'SingleArrowLine',
points: [ x1, y1,
x2,
y2,
x2-headlen*Math.cos(angle-Math.PI/6),
y2-headlen*Math.sin(angle-Math.PI/6),
x2,
y2,
x2-headlen*Math.cos(angle+Math.PI/6),
y2-headlen*Math.sin(angle+Math.PI/6)
],
shapeType: "line",
stroke: 'red',
strokeWidth: 2,
lineCap: 'round',
lineJoin: 'round',
draggable: false
});

/*Adding line Configure to Layer*/
layer.add(lineArrowConfig);

stage.add(layer);
stage.draw();

</script>
</body>
</html>