【JS进阶】Web API-JS原生animate(用例)
HTML代码
<div class="ball"></div>
CSS代码
.ball {
width: 100px;
height: 100px;
background-color: black;
border-radius: 50%;
}
JS代码
const ball = document.querySelector('.ball');
let prevX = 0, prevY = 0;
window.addEventListener('click', function(e) {
move(e.clientX, e.clientY);
})
function move(x, y) {
const rad = Math.atan2(y - prevY, x - prevX);
const deg = (rad * 100) / Math.PI;
ball.getAnimations().forEach((a) => a.cancel());
ball.animate(
[
{
transform: `translate(${prevX}px, ${prevY}px) rotate(${deg}deg)`,
easing: 'ease-out'
},
{
transform: `translate(${prevX}px, ${prevY}px) rotate(${deg}deg) scaleX(1.5)`,
offset: 0.6
},
{
transform: `translate(${x}px, ${y}px) rotate(${deg}deg) scaleX(1.5)`,
offset: 0.8
},
{
transform: `translate(${x}px, ${y}px) rotate(${deg}deg)`,
}
],
{
duration: 1000,
fill: 'forwards',
}
);
prevX = x;
prevY = y;
}