I´m just beginning to learn Html5 canvas, the main idea is to make an image move through multiple lines, creating paths, the total distance of the lines should be 10km, so i will be using 10 lines of 1km, using a javascript prompt, the user will say how many km or mts the image will advance. I think i´ll have to draw ten paths of lines, making the path of the image, but i still don´t know how to move the image through all the lines.
The following code, move the image once, with no line to follow, this is what i have so far:
$(function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
var pathArray = []; var enx = prompt("coordenada en x");
var eny = prompt("coordenada en y");
var num1 = parseInt(enx);
var num2 = parseInt(eny);
// Coordenada inicial
pathArray.push({
x: 50,
y: 50
});
pathArray.push({
x: num1,
y: num2
});
var polypoints = makePolyPoints(pathArray);
var width = 2;
var height = 5;
var position = 0;
var speed = 2;
animate();
var fps = 60;
function animate() {
setTimeout(function () {
requestAnimFrame(animate);
// calcular nueva posicion
position += speed;
if (position > polypoints.length - 1) {
return;
}
var pt = polypoints[position];
// dibujar
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
ctx.translate(pt.x, pt.y);
// Objeto de la imagen del corredor
img = new Image();
// url de imagen
img.src = "img/mono_animar.png";
ctx.drawImage(img,0,0);
ctx.restore();
}, 1000 / fps);
}
function makePolyPoints(pathArray)
{
var points = [];
for (var i = 1; i < pathArray.length; i++) {
var startPt = pathArray[i - 1];
var endPt = pathArray[i];
var dx = endPt.x - startPt.x;
var dy = endPt.y - startPt.y;
for (var n = 0; n <= 100; n++)
{
var x = startPt.x + dx * n / 100;
var y = startPt.y + dy * n / 100;
points.push({
x: x,
y: y
});
}
}
return (points);}});
But i need something like this:
http://jsfiddle.net/ExpertSystem/qxgkc/ Except that the user will type a number from 1 to 12km in order to move the image along the path lines.