JavaScript动画可以通过多种方式实现,最常见的有使用CSS动画、JavaScript自身的
setInterval
或requestAnimationFrame
方法、以及使用动画库如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)。