≪ Today I learned.
RSS購読
    公開日
    タグ
    JavaScript
    著者
    ダーシノ

    アニメーションで三角関数を使う

    Web Animations APIを使うことで簡単にアニメーションを管理できる。

    CSSの@keyframesで10°ずつ座標を書き表すことは大変だが、JavaScriptを使うことでより柔軟にアニメーションを制御できる。

    const item = document.querySelector('#item')
    
    const animationFrames = []
    const offset = { x: 100, y: 100 }
    const r = 100
    
    // 0°〜360°の範囲で10°毎の座標を計算し `translate(x, y)` にセットする
    for (let i = 0; i <= 360; i += 10) {
      // `angle * (Math.PI / 180)` で度数法を弧度法に変換する
      const x = Math.floor(Math.cos(i * (Math.PI / 180)) * r) + offset.x 
      const y = Math.floor(Math.sin(i * (Math.PI / 180)) * r) + offset.y
      
      animationFrames.push({
        // (x, y) = (cosθ, sinθ)
        transform: `translate(${x}px, ${y}px)`
      })
    }
    
    // Web Animation API
    item?.animate(animationFrames, { duration: 3000, iterations: Infinity })

    デモ