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> |
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
14.3 The Cat's Hat
Extend the cat animation defined earlier so that both the cat and his hat (
<img src="img/hat.png">
) orbit at opposite sides of the ellipse.Or make the hat circle around the cat. Or alter the animation in some other interesting way.
To make positioning multiple objects easier, it is probably a good idea to switch to absolute positioning. This means that
top
andleft
are counted relative to the top left of the document. To avoid using negative coordinates, which would cause the image to move outside of the visible page, you can add a fixed number of pixels to the position values.