JSFiddle - React, Tailwind, and code Playground

by mxxxl

HTML

<canvas id="1" width=19 height=94 style="border: 1px solid black;></canvas>

JavaScript

var canvas=document.getElementById("1");
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 pathStarts = { x: cw/2, y: 0  };
var pathEnds = { x: cw/2, y: ch };

var pathLength = ch;

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

var arrowLineLength=0;
var arrowLength=6;

requestAnimationFrame(animate);

function drawLineWithArrowhead(p1, p2, headLength) {

  // calc arrowhead points
  var x225 = p2.x + headLength * Math.cos(degreesInRadians225);
  var y225 = p2.y + headLength * Math.sin(degreesInRadians225);
  var x135 = p2.x + headLength * Math.sin(degreesInRadians135);
  var y135 = p2.y + headLength * Math.cos(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 * pct / ch;

  // calculate the new starting point of the arrow-line
  var x0 = pathStarts.x;
  var y0 = pathStarts.y - traveled;
  var lineStart = { x: x0, y: y0 };

  // calculate the new ending point of the arrow-line
  var x1 = pathStarts.x;
  var y1 = pathStarts.y + traveled;
  var lineEnd = { x: x1, y: y1 };

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw your arrow-line in it's newly animated position

  drawLineWithArrowhead(lineStart, lineEnd, arrowLength);

  pct++;
pct++;

  // request another loop in the...