Skip to content
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

Open
haizhilin2013 opened this issue Jul 20, 2019 · 6 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第96天 要实现一个js的持续动画,你有什么比较好的方法?

@haizhilin2013 haizhilin2013 added the js JavaScript label Jul 20, 2019
@NicholasBaiYa
Copy link

使用画布实现。

@haoolii
Copy link

haoolii commented Jul 22, 2019

GSAP

@geraldchen890806
Copy link

requestAnimationFrame

@Drowned-fish
Copy link

requestAnimationFrame,浏览器专门为js动画提供的API。

@xiaoqiangz
Copy link

setTimeout和 requestAnimationFrame都可以

@panpanxuebing
Copy link

panpanxuebing commented Dec 17, 2024

<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
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

7 participants