While this tutorial is about how to make moving banners, you can actually move any image across the screen this way.
In this animation, the x-coordinate value of the banner decreases as the banner
moves from right to left. The screen is cleared in between position changes.
function moveBanner()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
// Clear the screen
ctx.clearRect(0,0,700,100);
// Display the text in the new position
ctx.fillText("Believe", X, 50);
X -= 3;
// If the banner has reached the left end of the screen, resent the x-coordinate
if(X < -30)
X = 800
}
}
We have to call the moveBanner() function repeatedly at regular intervals. We will use the setInterval() method for this. The setInterval takes 2 parameters:
1. The function that is to be called at regular intervals 2. The interval in microseconds
setInterval(function() {changeColor()}, 50)
The above function will call moveBanner() function every 50 microseconds.
Now, let's put it all together
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
// Set the banner text attributes
ctx.fillStyle = "red";
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowBlur = 3;
ctx.shadowColor = "grey";
ctx.font = "30px verdana";
// Call the moveBanner() function repeatedly every 50 microseconds
setInterval(function() {moveBanner()}, 50)
}
}
function moveBanner()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
// Clear the screen
ctx.clearRect(0,0,700,100);
// Display the text in the new position
ctx.fillText("Believe", X, 50);
X -= 3;
// If the banner has reached the left end of the screen, resent the x-coordinate
if(X < -30)
X = 700
}
}
</script>
<title>Animation - Moving Banner</title>
</head>
</html>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas>
</body>
</html>