learner
learner

Reputation: 4818

No animation while using requestAnimationFrame in javascript

I want to rotate an image, but I am not getting any image rotation. How to fix this?

HTML file:

<html>
<head>
    <title>javascript</title>
</head>
<body>

    <p style="text-align: center" >
        <img src="kalam.jpg" style="position: relative">
    </p>

    <script type="text/javascript" src="code.js">
    </script>
</body>
</html>

code.js:

var kalam = document.querySelector ("img") ;
var angle = 0 , lastTime = null ;
function animate ( time ) {
    if ( lastTime != null )
        angle += ( time - lastTime ) * 0.001;
    lastTime = time ;
    kalam.style.top = ( Math.sin ( angle ) * 20) + " px ";
    kalam.style.left = ( Math.cos ( angle ) * 200) + " px ";
    requestAnimationFrame ( animate ) ;
}
requestAnimationFrame ( animate );

Upvotes: 2

Views: 54

Answers (1)

jaggedsoft
jaggedsoft

Reputation: 4038

The only problem is that your css says " px" instead of "px" because you can't have a space before you declare what unit of measure your css property is using.

Demo on JSBin

var kalam = document.querySelector("img") ;
var angle = 0 , lastTime = null ;
function animate ( time ) {
    if ( lastTime != null )
        angle += ( time - lastTime ) * 0.001;
    lastTime = time ;
    kalam.style.top = ( Math.sin ( angle ) * 40) + "px ";
    kalam.style.left = ( Math.cos ( angle ) * 90) + "px ";
    requestAnimationFrame ( animate ) ;
}
requestAnimationFrame ( animate );
<img src="http://static.jsbin.com/images/dave.min.svg" style="position:absolute;margin:40px 0 0 100px;max-height:90px">

Upvotes: 1

Related Questions