user180574
user180574

Reputation: 6094

Javascript: code with no animation with requestAnimationFrame?

I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?

<!doctype html>
<html>
<head>
  <title> My home page </title>
  <script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
  </script>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>

Thank you for the help.

Upvotes: 0

Views: 45

Answers (2)

Elad
Elad

Reputation: 2387

When the browser see a <script> tag, he stop rendering the page, and run the code inside.

So, the problem in the code that the line var cat = document.querySelector("img"); happen before the img is append to the document, so you query get nothing.

the only change you need to do- is to move the var cat = document.querySelector("img"); to under the body, like so:

</body>
<script>
    var cat = document.querySelector("img");
    requestAnimationFrame(animate);
</script>

</html>

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

If you look at the console, you will see that the cat is undefined.

This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.

If you move the code at the end of the body it will work.
Or you could run your code when the DOMContentLoaded event is fired.

<!doctype html>
<html>
<head>
  <title> My home page </title>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
</script>
<script>requestAnimationFrame(animate);</script>
</html>

Upvotes: 1

Related Questions