student101
student101

Reputation: 13

timeout function for simple html 5 javascript animation using canvas

I have been trying this simple animation with html 5 and javascript from here:

http://www.developphp.com/view.php?tid=1262

The code is follwoing:

<!-- Lesson by Adam Khoury @ www.developphp.com -->
<!-- Watch the video to get code explanation line by line -->
<!-- http://www.youtube.com/watch?v=hUCT4b4wa-8 -->
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
canvas{border:#666 1px solid;}
</style>
<script type="text/javascript">
function draw(x,y){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.save();
    ctx.clearRect(0,0,550,400);
    ctx.fillStyle = "rgba(0,200,0,1)";
    ctx.fillRect (x, y, 50, 50);
    ctx.restore(); 
    x += 1;
        var loopTimer = setTimeout('draw('+x+','+y+')',100);
}
</script>
</head>
<body>
<button onclick="draw(0,0)">Draw</button>
<canvas id="canvas" width="550" height="400"></canvas>
</body>  
</html> 

There is just one thing i don't understand in the code: in the setTimeout method what does the '+' before and after x and y do and why quotes are used to enclose +x+ and +y+?

Upvotes: 1

Views: 983

Answers (2)

Finoy Francis
Finoy Francis

Reputation: 696

'draw('+x+','+y+')' This is a just string concatination you will understand this by printing that string. following fiddle explains more.

http://jsfiddle.net/zebqqcee/

Upvotes: 3

Manjar
Manjar

Reputation: 3268

The setTimeout will execute the instruction with an eval, I mean this will execute when the timeout pop this:

eval('draw('+x+','+y+')');

If you don't like this syntax, I personally don't, you can use this:

var loopTimer = setTimeout(function() {
     draw(x,y);
},100);

Upvotes: 0

Related Questions