JSFiddle - React, Tailwind, and code Playground

by Przemek Misztal

HTML

<canvas id="canvas" width="600" height="350"></canvas>
<br>
<button id="button">GO</button>
    <h3>Hold left mouse button and draw a line then click "go"</h3>
    <p>The idea here is to track a route drawn by a user. After user draws a line it is stored in the variable "route". When user clicks "go" button the coordinates are used to animate a ball following the route</p>

CSS

#canvas {
    border:1px solid black;
}

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var route = []; 
var coords = {}; 
var x, y; 
var clicked = false; 

canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mousedown', function () {
    clicked = true;
});
canvas.addEventListener('mouseup', function () {
    clicked = false;
});

function draw(ev) {
    if (clicked) {
        x = ev.layerX;
        y = ev.layerY;
        
        coords = {
            x : x,
            y : y
        };
        route.push(coords);
        
        ctx.lineTo(x, y);
        ctx.stroke();
    } else {
        ctx.beginPath();
    }
}
// gracz - kulka
    ctx.arc(20, 20, 5, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
// idź do punktu
var i = 0;
var timer;
var go = function () {
    if(i < route.length) {
        ctx.clearRect(0, 0, canvas.width, canvas.height); 
        ctx.beginPath();
        ctx.arc(route[i].x, route[i].y, 5, 0, Math.PI * 2); 
        ctx.closePath();
        ctx.fill();
        i++;
       timer = setTimeout(go, 1000/60);
    } else clearTimeout(timer);
};
button.addEventListener("click", function(){
    timer = setTimeout(go, 1000/60);
    //console.log(route);
});