https://www.bilibili.com/video/BV1M34y1e7yH/?aid=810961392&cid=583416022&page=1
JavaScript and CSS animation showing flowers following the mouse pointer.
This effect is inspired by some websites. When the mouse is moved, a diffuse pattern of bubbles, red hearts or water waves appears around the mouse arrow. This effect has a strong visual appeal to the visitors of the webpage.
We can achieve this effect with plain HTML, JavaScript and CSS
The idea is as follows:
We listen to the mousemove
event, and when the event fires, create some div
, flowers, hearts and bubbles as background images for div
. and set their position to the position of the mouse pointer, then use settimeout
after a few seconds to delete it:
document.addEventListener("mousemove", function (e) {
let body = document.querySelector("body");
let flower = document.createElement("div");
let x = e.offsetX;
let y = e.offsetY;
flower.style.left = x + "px";
flower.style.top = y + "px";
body.appendChild(flower);
setTimeout(function () {
flower.remove();
}, 2000);
});
To make these flowers appear dynamic and random, we used Math.random()
to set random size and random rotation angle for each flower ( Math.random()
) is very useful).
let size = Math.random() * 80;
flower.style.width = 20 + size + "px";
flower.style.height = 20 + size + "px";
let rotation = Math.random() * 360;
flower.style.transform = `rotate(${rotation}deg)`;
The above is the part of JavaScript, we mainly use JS to create elements and set the initial state.
The animation part can be done using CSS. A total of 3 animation effects need to be implemented:
- Fade in after the flower is created
- Fade out before flowers are removed
- Movement spread and rotation of flowers
Fade in and out is achieved by setting several nodes opacity
:
@keyframes fadeInOut {
0%,
100% {
opacity: 0;
}
20%,
80% {
opacity: 1;
}
}
For mobile diffusion and rotation transform
can be implemented:
@keyframes move {
0% {
transform: translate(0) rotate(0deg);
}
100% {
transform: translate(300px) rotate(360deg);
}
}
These two keyframes
set the same time function and time function linear
, and the number of repetitions is set to infinite
:
div {
animation: fadeInOutc 2s linear infinite;
}
div:before {
animation: move 2s linear infinite;
}
Finally, there is a small effect worth mentioning, that is, when two flowers overlap, the upper flower should cast a shadow on the lower flower, which will make it look more realistic. This effect can be achieved with drop-shadow .
filter: drop-shadow(0 0 15px rgba(0, 0, 0, 0.5));
Hope you all like this effect!
Finally attached:
Demo: https://codesteppe.github.io/pointer-flowers/
Source code: https://github.com/CodeSteppe/pointer-flowers
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。