Javascript: function with parameters cause lag in animation -
First: I tried to search for a similar problem, but there really is no clue how should I tell it ? Title. So if any solution is already somewhere, please let me know.
I am trying to understand how OOP works in Javascript. I have some experience with the ActionScript I have written this code for practice, when the page is loaded, it moves the box from left to right. Now I want to type the code in such a way that I do not need hundreds of functions for many types of animation if I want to create many animated boxes.
This is my old code, which worked:
& lt; Script & gt; Var DX = 850; Var x = 0; Var y = 450; Function init () {b = document.getElementById ("box1"); Remove it(); } Window.requestAnimFrame = (function () {return window.requestAnimationFrame OR window.webkitRequestAnimationFrame OR window.mozRequestAnimationFrame OR window.oRequestAnimationFrame OR window.msRequestAnimationFrame OR function (/ * function * / callback, / * DOMElement * / element) {Window set Timeout (callback, 1000/60);};}) (); Move function () {x + = (dx - x) * 0.15; B.style.left = x + "px"; B.style.top = y + "px"; RequestAnimFrame (moveIt, b); } & Lt; / Script & gt; & Lt; / Head & gt; & Lt; Body onload = "init ()" & gt; & Lt; Div style = "width: 50px; height: 50px; background: blue; position: absolute;" Id = "box1" & gt; & Lt; / Div & gt; & Lt; / Body & gt;
And this is the second version, in which I tried to make the function more dynamic for animation. It seems to work, but it seems that the interval, or this animation does not, I'm not sure as it is difficult to check
As I am busy learning about these things, I am curious about any improvement for this.
You are running an infinite loop. You have to give a condition to stop the animation. In my code, this is just an example.
Try:
& lt; Div id = "box1" style = "position: absolute" & gt; X & lt; / Div & gt; & Lt; Button onclick = "init ();" & Gt; Test & lt; / Button & gt; & Lt; Script type = "text / javascript" & gt; Var xInit, yInit; Function init () {b = document.getElementById ("box1"); XInit = 0; YInit = 0; Move (b, xInit, 850, yInit, 450); } Move the function (Object, X, Endix, Y, Andy) {x + = Math.floor ((Exx - xInit) * 0.01); Y + = Math.floor ((Andy - yInit) * 0.01); Theobject.style.left = x + "px"; Theobject.style.top = y + "px"; If (x & lt; andx) request animation frame (function () {moveIt (theobject, x, endx, y, endy)}); } & Lt; / Script & gt;
Comments
Post a Comment