好,我先加了个纯文字的。
然后这段的话感觉可以稍微优化一下,减少对DOM的访问来提高性能:
function createAnimationElement() {
const img_width = 30;
const img_height = 30;
const blooming = document.createElement("div");
blooming.classList.add("blooming");
blooming.style.position = "absolute";
blooming.style.width = img_width + "px";
blooming.style.height = img_height + "px";
blooming.style.backgroundImage = `url([https://tb2.bdstatic.com/tb/editor/images/face/i_f25.png](https://tb2.bdstatic.com/tb/editor/images/face/i_f25.png))`;
return blooming;
}
function clickAnimation(e) {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
const base_x = e.clientX + scrollLeft - 15;
const base_y = e.clientY + scrollTop - 15;
const fadeTime = 600;
const frameTime = 10;
const frameCount = fadeTime / frameTime;
const elements = [];
const animations = [];
const clickCount = Math.floor(Math.random() * 3 + 3);
for (let i = 0; i < clickCount; i++) {
const blooming = createAnimationElement();
elements.push(blooming);
let frameIndex = 0;
let opacity = 1;
let scale = 1;
const rotate_max = 600;
const rotate_step = Math.floor(Math.random() * rotate_max / frameCount + 1);
const x_offset = Math.floor(Math.random() * 200 - 100);
const x_step = x_offset / frameCount;
const y_offset = Math.floor(Math.random() * 200 - 100);
const y_step = y_offset / frameCount;
animations.push({
blooming,
frameIndex,
opacity,
scale,
rotate_step,
x_step,
y_step
});
}
let animationId;
function animate() {
animationId = requestAnimationFrame(animate);
for (let i = 0; i < animations.length; i++) {
const {
blooming,
frameIndex,
opacity,
scale,
rotate_step,
x_step,
y_step
} = animations[i];
const rotate = Math.floor(frameIndex * rotate_step);
const x = frameIndex * x_step;
const y = frameIndex * y_step;
const newOpacity = 1 - frameIndex * (1 / frameCount);
const newScale = 1 - frameIndex * (1 / frameCount);
blooming.style.opacity = newOpacity > 0 ? newOpacity : 0;
blooming.style.transform = `rotate(${rotate}deg) scale(${newScale})`;
blooming.style.WebkitTransform = `rotate(${rotate}deg) scale(${newScale})`;
blooming.style.left = base_x + x + "px";
blooming.style.top = base_y + y + "px";
if (frameIndex < frameCount) {
animations[i].frameIndex = frameIndex + 1;
} else {
blooming.remove();
elements.splice(i, 1);
animations.splice(i, 1);
i--;
}
}
if (animations.length === 0) {
cancelAnimationFrame(animationId);
}
}
animate();
for (const blooming of elements) {
document.body.appendChild(blooming);
}
}
document.addEventListener("click", function (e) {
clickAnimation(e);
});
|