Last active
November 29, 2018 11:09
-
-
Save idiotWu/9561ff59d1f508969b6a3c77ac8047f6 to your computer and use it in GitHub Desktop.
This file contains 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
class Nyan { | |
constructor(speed = 3) { | |
this.x = 0; | |
this.y = 0; | |
this.max_x = 0; | |
this.max_y = 0; | |
this.vx = this.vy = speed; | |
const img = this.img = new Image(); | |
img.src = 'http://www.nyan.cat/images/thumbs/balloon.gif'; | |
img.style.position = 'fixed'; | |
img.style.top = '0px'; | |
img.style.left = '0px'; | |
img.style.zIndex = '99999'; | |
document.body.appendChild(img); | |
img.addEventListener('load', () => { | |
this.init(); | |
}); | |
window.addEventListener('resize', this.refresh.bind(this)); | |
} | |
init() { | |
this.refresh(); | |
this.x = Math.random() * this.max_x | 0; | |
this.y = Math.random() * this.max_y | 0; | |
this.play(); | |
} | |
play() { | |
this.update(); | |
this.render(); | |
this.rafID = requestAnimationFrame(() => { | |
this.play(); | |
}); | |
} | |
pause() { | |
cancelAnimationFrame(this.rafID); | |
} | |
refresh() { | |
const width = window.innerWidth; | |
const height = window.innerHeight; | |
this.max_x = width - this.img.width; | |
this.max_y = height - this.img.height; | |
this.x = Math.min(this.max_x, this.x); | |
this.y = Math.min(this.max_y, this.y); | |
} | |
update() { | |
const { | |
vx, vy, | |
max_x, max_y, | |
} = this; | |
const nextX = this.x + vx; | |
const nextY = this.y + vy; | |
if (nextX <= 0 || nextX >= max_x) { | |
this.x = Math.max(0, Math.min(nextX, max_x)); | |
this.vx = -vx; | |
} else { | |
this.x = nextX; | |
} | |
if (nextY <= 0 || nextY >= max_y) { | |
this.y = Math.max(0, Math.min(nextY, max_y)); | |
this.vy = -vy; | |
} else { | |
this.y = nextY; | |
} | |
} | |
render() { | |
const { | |
img, | |
x, y, | |
} = this; | |
img.style.transform = `translate3d(${x}px, ${y}px, 0) rotateY(${this.vx >= 0 ? 0 : 180}deg)`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment