Hello everyone,
I'd like to make an animation of a single line using JavaScript and Canvas tag. I'm able to do it without any problems, except:
it works fine if you're trying to do a straight line - I have an interval (10ms) adding 1px, so if it's going from 150px (x)/20px (Y) to 150px (X)/200px (Y) - everything looks cool.
Problem is with lines going to the right or left -- eg from 150px (x) / 20px (Y) to 35px (X)/200px (Y)
Here my animation fails because by adding 1px every 10ms to both X and Y makes the line hit left side (35px) first and then going from there to my end point Y.
Here's my code (you will need Firefox or Opera) -- as you can see line hits left side sooner and that's my problem. :(
<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>