Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Björn Norén
9,569 PointsCanvas | Move box animation
Hello there! I have this code there a blue square is moving from the left corner to the right, but it occurs instantly and I'm trying to figure out how to slow down the speed, is there anyone who knows? And could you show me how to solve it?
I have tried setTimeout(); and setInterval();, but I'm failing at using the correct
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
margin: 40px; background:#666;
}
#my_canvas {
background:#fff; border:#000 1px solid;
}
</style>
<script>
function draw(){
var canvas = document.getElementById("my_canvas");
var ctx = canvas.getContext("2d");
var x = 0;
for (var i = 0; i < 500; i++){
ctx.fillStyle = 'blue';
ctx.fillRect(x, 0, 100, 100);
x++;
}
}
window.onload = draw;
</script>
</head>
<body>
<canvas id="my_canvas" width="500" height="500">
</canvas>
</body>
</html>
1 Answer
Steven Parker
243,318 PointsHere's an example using setInterval:
function draw() {
var canvas = document.getElementById("my_canvas");
var ctx = canvas.getContext("2d");
var x = 0;
function moveBox() {
ctx.fillStyle = 'blue';
ctx.fillRect(x, 0, 100, 100);
ctx.fillStyle = 'white'; // move not stretch
ctx.fillRect(x - 1, 0, 1, 100);
if (++x > 400)
clearInterval(iv);
}
var iv = setInterval(moveBox, 10);
}
window.onload = draw;
Björn Norén
9,569 PointsBjörn Norén
9,569 PointsSuuuuuper huge thanks!