I would like to make a single line animation using JavaScript and Canvas tags. I can do this without any problems except:
it works fine if you try to make a straight line - I have an interval (10 ms) adding 1px, so if it goes from 150px (x) / 20px (Y) to 150px (X) / 200px (Y) - that's it looks cool.
The problem is that the lines go right or left - for example, from 150px (x) / 20px (Y) to 35px (X) / 200px (Y)
Here, my animation fails, because by adding 1px every 10 ms to X and Y, the line first goes to the left side (35px) and then goes from there to my endpoint Y.
Here is my code (you will need Firefox or Opera), as you can see that the line is on the left side earlier and that my problem is :(
<html>
<script type="text/javascript" src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
<style>
body {background: #fff; color: #ccc;}
</style>
<script type="text/javascript">
var startpointx = 150;
var startpointy = 25;
var curposx = 150;
var curposy = 25;
var myinterval;
function init() {
myinterval = setInterval( ' animate(35, 250) ', 10);
}
function random (n)
{
return (Math.floor (Math.random() * n));
}
function animate(endpointx, endpointy) {
if (curposx == endpointx && curposy == endpointy){
clearInterval(myinterval);
drawShape(endpointx, endpointy);
return false;
} else {
if(curposx != endpointx){
if(endpointx > curposx) {
curposx = curposx + 1;
} else {
curposx = curposx - 1;
}
}
if(curposy <= endpointy){
curposy = curposy + 1;
}
}
drawShape(curposx, curposy, "#000");
}
function drawShape(tendpointx, tendpointy, clor){
var canvas = document.getElementById('cnvs');
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,310,400);
ctx.strokeStyle = clor;
ctx.beginPath();
ctx.moveTo(startpointx ,startpointy );
ctx.lineTo(tendpointx,tendpointy);
ctx.stroke();
}
init();
</script>
<body>
<canvas id="cnvs" width="310" height="400" style="border: 1px solid #ccc;"></canvas>
</body>
</html>