Created
March 26, 2018 08:42
-
-
Save jonurry/6d8616287fc11c14a12ac03f27670755 to your computer and use it in GitHub Desktop.
14.3 The Cat's Hat (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
Math.cos
andMath.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-timeMath.PI
. This can be useful for putting the hat on the opposite side of the orbit.