1

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+?

2

2 Answers 2

3

'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/

Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

thanks. is it possible to draw another green little rectangle starting from bottom-right of the canvas to bottom left within the same context?
yes, it is possible, but you will need to parametrized the color, which is used in ctx.fillStyle = "rgba(0,200,0,1)" and also the direction which is used in x += 1; you function header should look like function draw(x,y,color,direction); and you will call it 2 times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.