style[options.property] = Math.ceil(newval) + 'px';
}else{
// set the element to its final spot
el.style[options.property] = options.to + 'px';
// clear the interval. the intervalID is available
// via the closure
clearInterval(intervalID);
}
}
var intervalID = setInterval(animate, 1000 / fps);
}
CHAPTER 6 n VISUAL EFFECTS 134
This animation object can now modify a DOM property upon instantiation. But what if
you want more control on the animation process (for example, being able to decide when to
start, stop, or reset the animation)? Let??™s extend the object further with some new methods.
You??™ll add start() and stop(), which will work like the play and stop buttons on a tape
recorder (er, CD player??”sorry, I mean MP3 player). However, while you??™re here, let??™s add a
couple of extra methods: gotoStart() and gotoEnd(). Using the multimedia machine analogy,
they will enable you to rewind or fast forward the animation, if need be.
There are two key changes that you need to make. The first is to have the setInterval()
not run automatically on instantiation, but to have it only when you run start(). The other
change is to offer up a public API by returning an object as a result of instantiation (this is a
great example of the encapsulation that was covered in Chapter 3):
function Animation(options)
{
var el = options.element;
if(typeof el == 'string') el = document.getElementById(options.
Pages:
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206