Javascript Animations
You can use JavaScript to make a complex animation that includes, but is not limited to, the elements mentioned below:
- Fireworks
- Fade Effect
- Roll-in or Roll-out
- Page-in or Page-out
- Object movements
You may be interested in Script.Aculo.us, a JavaScript-based animation library.
This tutorial will teach you how to make an animation using JavaScript.
A logical equation or function can be used to transfer a number of DOM elements (img />, div>, or any other HTML element) around the page using JavaScript.
The following two JavaScript functions are widely used in animation programs.
- setTimeout( function, duration) is a function that allows you to set a timer for a certain amount of After milliseconds have passed, this feature calls function.
- setInterval(function, duration) setInterval(function, duration) setInterval(function, duration) setInterval After every millisecond, this function calls function.
- clearTimeout(setTimeout variable) / clearTimeout(setTimeout variable) / clearTimeout(setTimeout Any timer set by the
setTimeout()
functions is cleared when this function is called.
A number of attributes of a DOM object, including its location on the screen, can be set using JavaScript. You can place an object anywhere on the screen by changing its top and left attributes. The syntax is as follows.
// This will help to Set distance
// from left edge of the screen.
object.style.left = distance in pixels or points;
or
// This will help to Set distance
// from top edge of the screen.
object.style.top = distance in pixels or points;
Animation that is automatically created
We saw how a picture moves to the right with each click in the previous example. Using the JavaScript feature setTimeout()
, we may automate this method as follows:
More approaches have been added here. So, let's take a look at what's new here.
To set the location of imgObj
, the moveRight()
function calls the setTimeout()
function.
We've introduced a new function stop()
that resets the object to its initial location and clears the timer set by the setTimeout()
function.
As an illustration
Take a look at the code below for an example.
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
var imgObj = null;
var animate;
clearTimeout(animate);
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
clearTimeout(animate);
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
</script>
</head>
<body>
<form>
<img id="myImage" src = "img.jpg" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>
Live Demo!