-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第96天 要实现一个js的持续动画,你有什么比较好的方法? #964
Labels
js
JavaScript
Comments
使用画布实现。 |
GSAP |
requestAnimationFrame |
requestAnimationFrame,浏览器专门为js动画提供的API。 |
setTimeout和 requestAnimationFrame都可以 |
<div id="move"></div>
<button id="start">开始</button>
<button id="stop">停止</button> ;(function() {
let el = document.getElementById('move')
let done = false;
let left = 0;
let top = 0;
let direction = 'right' // left right down up
let requestId = null
function step (timestamp) {
switch (direction) {
case 'right':
left += 10
if (left === 200) {
direction = 'down'
}
break
case 'down':
top += 10
if (top === 200) {
direction = 'left'
}
break;
case 'left':
left -= 10
if (left === 0) {
direction = 'up'
}
break;
case 'up':
top -= 10
if (top === 0) {
direction = 'right'
}
break;
}
el.style.left = `${left}px`
el.style.top = `${top}px`
if (!done) {
requestId = window.requestAnimationFrame(step);
}
}
document.getElementById('start').onclick = () => {
done = false
window.cancelAnimationFrame(requestId)
requestId = window.requestAnimationFrame(step)
}
document.getElementById('stop').onclick = () => {
done = true
}
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
第96天 要实现一个js的持续动画,你有什么比较好的方法?
The text was updated successfully, but these errors were encountered: