Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 26, 2018 08:42
Show Gist options
  • Save jonurry/6d8616287fc11c14a12ac03f27670755 to your computer and use it in GitHub Desktop.
Save jonurry/6d8616287fc11c14a12ac03f27670755 to your computer and use it in GitHub Desktop.
14.3 The Cat's Hat (Eloquent JavaScript Solutions)
<style>body { min-height: 400px }</style>
<img src="img/cat.png" id="cat" style="position: absolute">
<img src="img/hat.png" id="hat" style="position: absolute">
<img src="img/hat.png" id="hat2" style="position: absolute">
<script>
let cat = document.querySelector("#cat");
let hat = document.querySelector("#hat");
let angle = 0;
let lastTime = null;
function animate(time) {
if (lastTime != null) angle += (time - lastTime) * 0.001;
lastTime = time;
cat.style.top = (Math.sin(angle) * 40 + 140) + "px";
cat.style.left = (Math.cos(angle) * 200 + 330) + "px";
hat.style.top = (Math.sin(angle + Math.PI) * 40 + 140) + "px";
hat.style.left = (Math.cos(angle + Math.PI) * 200 + 330) + "px";
hat2.style.top = (Math.sin(angle) * 50 + 90) + "px";
hat2.style.left = (Math.cos(angle) * 200 - Math.cos(angle) * 20 + 340) + "px";
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
@jonurry
Copy link
Author

jonurry commented Mar 26, 2018

Hints

Math.cos and Math.sin measure angles in radians, where a full circle is 2π. For a given angle, you can get the opposite angle by adding half of this, one-time Math.PI. This can be useful for putting the hat on the opposite side of the orbit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment