<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);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.