-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclick-spark.js
77 lines (66 loc) · 1.97 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
class ClickSpark extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
this.shadowRoot.innerHTML = this.createSpark();
this.svg = this.shadowRoot.querySelector("svg");
this._parent = this.parentNode;
this._parent.addEventListener("click", this);
}
disconnectedCallback() {
this._parent.removeEventListener("click", this);
delete this._parent;
}
handleEvent(e) {
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) {
this.style.left = e.pageX - this.clientWidth / 2 + "px";
this.style.top = e.pageY - this.clientHeight / 2 + "px";
}
createSpark() {
return `
<style>
:host {
position: absolute;
pointer-events: none;
}
</style>
<svg width="30" height="30" viewBox="0 0 100 100" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" stroke="var(--click-spark-color, currentcolor)" transform="rotate(-20)">
${Array.from(
{ length: 8 },
(_) =>
`<line x1="50" y1="30" x2="50" y2="4" stroke-dasharray="30" stroke-dashoffset="30" style="transform-origin: center" />`
).join("")}
</svg>
`;
}
}
customElements.define("click-spark", ClickSpark);