JSFiddle - React, Tailwind, and code Playground

by mxxxl

HTML

<canvas id="canvas" width=300 height=300></canvas>

CSS

#canvas{border:1px solid red; margin:0 auto; }

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


// constants (could be declared as globals outside this function)
var PI = Math.PI;
var degreesInRadians225 = 225 * PI / 180;
var degreesInRadians135 = 135 * PI / 180;

var p1 = { x: 0,   y: 10 };
var p2 = { x: 10, y: 100 };

var pathStarts = { x: p1.x, y: p1.y };
var pathEnds = { x: p2.x, y: p2.y };

var dx = pathEnds.x - pathStarts.x;
var dy = pathEnds.y - pathStarts.y;

var pathLength = Math.sqrt(dx * dx + dy * dy);
var pathAngle = Math.atan2(dy, dx);



// pct will be incremented from 0 to 100
// At 100 the arrow-line will have its arrowhead at P2
var pct = 0;

var arrowLineLength=10;
var arrowLength=10;

requestAnimationFrame(animate);


function drawLineWithArrowhead(p1, p2, headLength) {

  // calc the angle of the line
  var dx = p2.x - p1.x;
  var dy = p2.y - p1.y;
  var angle = Math.atan2(dy, dx);

  // calc arrowhead points
  var x225 = p2.x + headLength * Math.cos(angle + degreesInRadians225);
  var y225 = p2.y + headLength * Math.sin(angle + degreesInRadians225);
  var x135 = p2.x + headLength * Math.cos(angle + degreesInRadians135);
  var y135 = p2.y + headLength * Math.sin(angle + degreesInRadians135);

  // draw line plus arrowhead
  ctx.beginPath();
  // draw the line from p1 to p2
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
  // draw partial arrowhead at 225 degrees
  ctx.moveTo(p2.x, p2.y);
  ctx.lineTo(x225, y225);
  // draw partial arrowhead at 135 degrees
  ctx.moveTo(p2.x, p2.y);
  ctx.lineTo(x135, y135);
  // stroke the line and arrowhead
  ctx.stroke();
}

function animate(time) {

  // calculate how far the line has already animated
  // shorten the distance by the length used by the arrowLine
  var traveled = (pathLength - arrowLineLength) * pct / 100;

  // calculate the new starting point of the arrow-line
  var x0 = pathStarts.x + traveled * Math.cos(pathAngle);
  var y0 = pathStarts.y + traveled *...