JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="test" width="400" height="200"></canvas>
JavaScript
window.onload = function(e) {
var canvas = document.getElementById('test');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
var clear = function() {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
};
var target = {
x : width / 2 + 60,
y : 20
};
var start = {
x : width / 2,
y : height
};
var current = {
x : 0,
y : 0
};
var growth = 0;
var renderer = setInterval(function() {
clear();
// draw target
context.fillStyle = 'blue';
context.fillRect(target.x - 5, target.y - 5, 10, 10);
// draw static line to target
context.strokeStyle = 'green';
context.beginPath();
context.moveTo(start.x, start.y);
context.lineTo(target.x, target.y);
context.closePath();
context.stroke();
// calculate line endpoint
current.x = start.x + (target.x - start.x) * growth;
current.y = start.y + (target.y - start.y) * growth;
// draw segment of line to target
context.strokeStyle = 'red';
context.beginPath();
context.moveTo(start.x, start.y);
context.lineTo(current.x, current.y);
context.closePath();
context.stroke();
// grow segment
growth += 1 / 100;
// reset to start
if (growth >= 1)
{
growth = 0;
}
}, 1000 / 60);
};