-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclick-spark.js
99 lines (82 loc) · 2.29 KB
/
click-spark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class ClickSpark extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.root = document.documentElement;
this.svg;
}
get activeEls() {
return this.getAttribute("active-on");
}
connectedCallback() {
this.setupSpark();
this.root.addEventListener("click", (e) => {
if (this.activeEls && !e.target.matches(this.activeEls)) return;
this.setSparkPosition(e);
this.animateSpark();
});
}
animateSpark() {
let sparks = [...this.svg.children];
let size = parseInt(sparks[0].getAttribute("y1"));
let offset = size / 2 + "px";
let keyframes = (i) => {
let deg = `calc(${i} * (360deg / ${sparks.length}))`;
return [
{
strokeDashoffset: size * 3,
transform: `rotate(${deg}) translateY(${offset})`
},
{
strokeDashoffset: size,
transform: `rotate(${deg}) translateY(0)`
}
];
};
let options = {
duration: 660,
easing: "cubic-bezier(0.25, 1, 0.5, 1)",
fill: "forwards"
};
sparks.forEach((spark, i) => spark.animate(keyframes(i), options));
}
setSparkPosition(e) {
let rect = this.root.getBoundingClientRect();
this.svg.style.left =
e.clientX - rect.left - this.svg.clientWidth / 2 + "px";
this.svg.style.top =
e.clientY - rect.top - this.svg.clientHeight / 2 + "px";
}
setupSpark() {
this.createSvgTemplate();
this.svg = this.shadowRoot.querySelector("svg");
}
createSvgTemplate() {
let template = `
<style>
:host {
display: contents;
}
svg {
pointer-events: none;
position: absolute;
rotate: -20deg;
stroke: var(--click-spark-color, currentcolor);
}
line {
stroke-dasharray: 30;
stroke-dashoffset: 30;
transform-origin: center;
}
</style>
<svg width="30" height="30" viewBox="0 0 100 100" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="4">
${Array.from(
{ length: 8 },
(_) => `<line x1="50" y1="30" x2="50" y2="4"/>`
).join("")}
</svg>
`;
this.shadowRoot.innerHTML = template;
}
}
customElements.define("click-spark", ClickSpark);