【发布时间】:2020-07-27 04:05:14
【问题描述】:
我想制作一个div,它跟随光标并同时作为动画增长/收缩。
我使用top 和left 更改了div 的位置,但动画有时有点不稳定。
我想使用translate3d 来制作animations smooth,但我很难将translate3d 与scale 结合起来
const moveCursor = event => {
const cursorWidth = cursor.offsetWidth / 2;
cursor.style.left = event.pageX - cursorWidth + "px";
cursor.style.top = event.pageY - cursorWidth + "px";
};
我想修改此函数以使用 translate3d 代替 top 和 left 并保留动画中现有的 scale 转换值
我想出了这个,但它不起作用
const moveCursor = event => {
const cursorWidth = cursor.offsetWidth / 2;
const xCoordinate = event.pageX - cursorWidth + "px";
const yCoordinate = event.pageY - cursorWidth + "px";
const matrix = window.getComputedStyle(cursor).transform;
const scalingFactor = parseFloat(matrix.split(",")[3]);
cursor.style.transform = `translate3d(${xCoordinate},${yCoordinate},0px) scale(${scalingFactor})`
};
我哪里错了?
const cursor = document.getElementById("cursor");
const moveCursor = event => {
const cursorWidth = cursor.offsetWidth / 2;
cursor.style.left = event.pageX - cursorWidth + "px";
cursor.style.top = event.pageY - cursorWidth + "px";
};
document.addEventListener("mousemove", moveCursor);
#background {
position: relative;
height: 100vh;
width: 100vw;
overflow: hidden;
background-color: #0e0e0e;
color: ivory;
font-size: 3rem;
text-align: center;
}
#cursor {
width: 15rem;
height: 15rem;
will-change: transform;
background: ivory;
position: absolute;
mix-blend-mode: difference;
border-radius: 50%;
animation: grow-shrink 4s infinite alternate;
}
@keyframes grow-shrink {
0% {
transform: scale(1.2);
}
25% {
transform: scale(0.8);
}
50% {
transform: scale(1.2);
}
75% {
transform: scale(0.8);
}
100% {
transform: scale(1);
}
}
<div id="background">
Lorem Ipsum
<div id="cursor"></div>
</div>
【问题讨论】:
标签: javascript html css css-animations translate3d