Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

Activity

NicholasBaiYa

NicholasBaiYa commented on Jul 21, 2019

@NicholasBaiYa

使用画布实现。

haoolii

haoolii commented on Jul 22, 2019

@haoolii

GSAP

geraldchen890806

geraldchen890806 commented on Jul 22, 2019

@geraldchen890806

requestAnimationFrame

Drowned-fish

Drowned-fish commented on Jul 24, 2019

@Drowned-fish

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

xiaoqiangz

xiaoqiangz commented on Jun 24, 2022

@xiaoqiangz

setTimeout和 requestAnimationFrame都可以

panpanxuebing

panpanxuebing commented on Dec 17, 2024

@panpanxuebing
<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

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@geraldchen890806@xiaoqiangz@haoolii@panpanxuebing

        Issue actions

          [js] 第96天 要实现一个js的持续动画,你有什么比较好的方法? · Issue #964 · haizlin/fe-interview