animation

Web Animation API 的执行效率高,不改变DOM树,不需要浏览器主线程参与

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Animation API</title>
    <link rel="stylesheet" href="./style/index3.css">
</head>
<body>
    <div class="ball"></div>
    <script src="./js/index3.js"></script>
</body>
</html>
body{
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 100vh;
    background-color: #000;
}
.ball{
    position: absolute;
    width: 50px;
    height: 50px;
    background-color: #d19b5d;
    border-radius: 50%;
}
const ball=document.querySelector('.ball')

window.addEventListener('click',(e)=>{
    const pointer = document.createElement('div')
    pointer.classList.add('pointer')
    pointer.style.left = `${e.clientX}px`
    pointer.style.top = `${e.clientY}px`
    document.body.appendChild(pointer)
    pointer.addEventListener('animationend',()=>{
        pointer.remove()
    })
})

function init(){
    const x = window.innerWidth/2
    const y = window.innerHeight/2
    ball.style.transform = `translate(${x}px,${y}px)`
}
init()

window.addEventListener('click',(e)=>{
    const x = e.clientX
    const y = e.clientY
    move(x,y)
})

function move(x,y){
    // 获取当前位置
    const rect = ball.getBoundingClientRect()
    const ballX = rect.left + rect.width/2
    const ballY = rect.top + rect.height/2

    // 为了提升性能,防止多次点击产生过多动画,每次移动前都取消当前动画
    ball.getAnimations().forEach(animation=>animation.cancel())

    // 计算拉升角度
    const angle = Math.atan2(y-ballY,x-ballX) * 180 / Math.PI
    console.log(angle)

    // 传入关键帧和动画配置
    ball.animate([
        {transform: `translate(${ballX}px,${ballY}px) rotate(${angle}deg)`}, 
        {transform: `translate(${ballX}px,${ballY}px) scaleX(1.5) rotate(${angle}deg)`, offset: 0.6}, 
        {transform: `translate(${x}px,${y}px) scaleX(1.5) rotate(${angle}deg)`, offset: 0.8},
        {transform: `translate(${x}px,${y}px) rotate(${angle}deg)`}
    ],{
        duration: 500,
        easing: 'ease-in-out',
        fill: 'forwards'
    })
}

QQ20251020-14926

posted @ 2025-10-20 14:10  原语  阅读(7)  评论(0)    收藏  举报