javascript animate动画

JavaScript动画可以通过多种方式实现,最常见的有使用CSS动画、JavaScript自身的setIntervalrequestAnimationFrame方法、以及使用动画库如GreenSock(GSAP)等

animate api 是和css动画差不多,利用关键帧

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球移动</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div id="ball"></div>
    <script src="./index.js"></script>
</body>
</html>

css 

body{
    width: 100vw;
    height: 100vh;
    background-color: black;
    overflow: hidden;
}
#ball{
    --size:100px;
    width: var(--size);
    height: var(--size);
    background-color: red;
    border-radius: 100%;
    margin-left:calc(var(--size)/2*-1);
    margin-top:calc(var(--size)/2*-1);
}

 js

let ball = document.getElementById('ball');

window.onclick = (e)=>{
    let x = e.offsetX;
    let y = e.offsetY;
    // 移动
    moveTo(x,y)
}
// 取消小球的点击事件
ball.onclick = e=>{
    e.stopPropagation()
}
function moveTo(x,y){
    // 小球当前位置
    let curry = ball.getBoundingClientRect().top + ball.offsetWidth / 2;
    let currx = ball.getBoundingClientRect().left + ball.offsetWidth / 2;
    // 清空动画
    ball.getAnimations().forEach(animation=>animation.cancel());
    // 小球旋转角度
    // 反正切 获得弧度
    let radian = Math.atan2(y-curry,x-currx);
    // 弧度转角度
    let deg = (radian * 180) / Math.PI;
    ball.animate([
        {
            transform: `translate(${currx}px,${curry}px) rotate(${deg}deg)`,
        },
        {
            transform: `translate(${currx}px,${curry}px) rotate(${deg}deg) scalex(1.5)`,
            offset:0.6
        },
        {
            transform: `translate(${currx}px,${curry}px) rotate(${deg}deg) scalex(1.5)`,
            offset:0.8
        },
        {
           transform: `translate(${x}px,${y}px) rotate(${deg}deg)`,
        }
    ], {
        duration:1000,
        fill:"forwards"
    })
}

atan2: 反正切

反正切函数(arctan),也称为tan⁻¹,是三角函数的一种,它是正切函数的反函数。反正切函数的作用是,给定一个值(通常是一个比值),它返回该比值的角度。在数学中,反正切函数通常表示为tan⁻¹(x),其中x是一个实数。反正切函数的定义域是所有实数,其值域是(-π/2, π/2)。

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_最初の心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值