Помогите переделать код создания частиц по нажатию на кнопку, в функцию создания частиц в любом месте через JS
взял с сайта эффект создания частиц по клику кнопки, собственно вот он
function pop (e) {
let amount = 30;
switch (e.target.dataset.type) {
case 'shadow':
case 'line':
amount = 60;
break;
}
if (e.clientX === 0 && e.clientY === 0) {
const bbox = e.target.getBoundingClientRect();
const x = bbox.left + bbox.width / 2;
const y = bbox.top + bbox.height / 2;
for (let i = 0; i < 30; i++) {
createParticle(x, y, e.target.dataset.type);
}
} else {
for (let i = 0; i < amount; i++) {
createParticle(e.clientX, e.clientY, e.target.dataset.type);
}
}
}
function createParticle (x, y, type) {
const particle = document.createElement('particle');
document.body.appendChild(particle);
let width = Math.floor(Math.random() * 30 + 8);
let height = width;
let destinationX = (Math.random() - 0.5) * 1000;
let destinationY = (Math.random() - 0.5) * 1000;
let rotation = Math.random() * 520;
let delay = Math.random() * 200;
switch (type) {
case 'shadow':
var color = `hsl(${Math.random() * 50 + 200}, 70%, 50%)`; // Цвет
particle.style.boxShadow = `0 0 ${Math.floor(Math.random() * 10 + 10)}px ${color}`; // Тень
particle.style.background = color;
particle.style.borderRadius = '50%'; // Радиус
width = height = Math.random() * 100 + 4; // Размеры
break;
}
particle.style.width = `${width}px`;
particle.style.height = `${height}px`;
const animation = particle.animate([
{
transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
opacity: 1
},
{
transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px) rotate(${rotation}deg)`,
opacity: 0
}
], {
duration: Math.random() * 1000 + 5000, // Продолжительность всех эффектов
easing: 'cubic-bezier(0, .9, .57, 1)',
delay: delay
});
animation.onfinish = removeParticle;
}
function removeParticle (e) {
e.srcElement.effect.target.remove();
}
if (document.body.animate) {
document.querySelectorAll('button').forEach(button => button.addEventListener('click', pop));
}
particle {
position: fixed;
top: 0;
left: 0;
opacity: 0;
pointer-events: none;
background-repeat: no-repeat;
background-size: contain;
}
.div {
background: rgb(98, 104, 252, 0.7);
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
button {
position: absolute;
left: 50%;
top: 5em;
}
<div clss="div">
<button data-type="shadow">Кнопка</button>
</div>
Однако мне хочется использовать данный код создания частиц без кнопки. я пробовал сам пересобрать, у меня не получилось. Скажите пожалуйста как вызывать создание этих частиц в каком то месте через JS.
Ответы (1 шт):
Автор решения: Pr0gramm1st
→ Ссылка
Полагаю, это можно решить вот так:
function pop(effectType, coordinateX, coordinateY, bounding = {
'width': 60,
'height': 21,
'top': 250,
'left': 250
}) {
let amount = 30;
switch (effectType) {
case 'shadow':
case 'line':
amount = 60;
break;
}
if (coordinateX === 0 && coordinateY === 0) {
const bbox = bounding;
const x = bbox.left + bbox.width / 2;
const y = bbox.top + bbox.height / 2;
for (let i = 0; i < 30; i++) {
createParticle(x, y, effectType);
}
} else {
for (let i = 0; i < amount; i++) {
createParticle(coordinateX, coordinateY, effectType);
}
}
}
function createParticle(x, y, type) {
const particle = document.createElement('particle');
document.body.appendChild(particle);
let width = Math.floor(Math.random() * 30 + 8);
let height = width;
let destinationX = (Math.random() - 0.5) * 1000;
let destinationY = (Math.random() - 0.5) * 1000;
let rotation = Math.random() * 520;
let delay = Math.random() * 200;
switch (type) {
case 'shadow':
var color = `hsl(${Math.random() * 50 + 200}, 70%, 50%)`; // Цвет
particle.style.boxShadow = `0 0 ${Math.floor(Math.random() * 10 + 10)}px ${color}`; // Тень
particle.style.background = color;
particle.style.borderRadius = '50%'; // Радиус
width = height = Math.random() * 100 + 4; // Размеры
break;
}
particle.style.width = `${width}px`;
particle.style.height = `${height}px`;
const animation = particle.animate([{
transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
opacity: 1
},
{
transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px) rotate(${rotation}deg)`,
opacity: 0
}
], {
duration: Math.random() * 1000 + 5000, // Продолжительность всех эффектов
easing: 'cubic-bezier(0, .9, .57, 1)',
delay: delay
});
animation.onfinish = removeParticle;
}
function removeParticle(e) {
e.srcElement.effect.target.remove();
}
//if (document.body.animate) {
//document.querySelectorAll('button').forEach(button => button.addEventListener('click', pop));
//}
pop('shadow', 250, 250); //Вызываем в любом месте с теми параметрами, какие нам необходимы
particle {
position: fixed;
top: 0;
left: 0;
opacity: 0;
pointer-events: none;
background-repeat: no-repeat;
background-size: contain;
}
.div {
background: rgb(98, 104, 252, 0.7);
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
button {
position: absolute;
left: 50%;
top: 5em;
}
<div class="div">
<button data-type="shadow">Кнопка</button>
</div>
P.S. С вашего позволения исправил опечатку в строке <div class="div">