-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmooth.js
More file actions
66 lines (60 loc) · 1.74 KB
/
Copy pathsmooth.js
File metadata and controls
66 lines (60 loc) · 1.74 KB
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
/**
* Create a panel div with text.
* @param {string} txt to be added to element
*/
export function create(txt) {
const e = document.createElement('div');
e.className = 'panel';
if (txt) e.textContent = txt;
return e;
}
/**
* Assign a random data-score to each element.
*/
export function randomizeScores(elements) {
elements.forEach((el) => {
el.dataset.score = Math.round(Math.random() * 20);
});
}
/**
* Record each element's current layout position in data-x/data-y.
* offsetLeft/offsetTop reflect layout flow, not CSS transforms.
*/
export function getOriginalLocations(elements) {
elements.forEach((el) => {
el.dataset.x = el.offsetLeft;
el.dataset.y = el.offsetTop;
});
}
/**
* Set CSS custom properties for translation and hue.
*/
function applyTransform(moveThis, referenceElem) {
const tx = Number(referenceElem.dataset.x) - Number(moveThis.dataset.x);
const ty = Number(referenceElem.dataset.y) - Number(moveThis.dataset.y);
moveThis.style.setProperty('--tx', `${tx}px`);
moveThis.style.setProperty('--ty', `${ty}px`);
moveThis.style.setProperty('--hue', `${moveThis.dataset.score * 15}deg`);
}
/**
* Sort elements by data-score (descending) and apply the transform
* needed to move each element into its sorted slot.
*/
export function sort(elements) {
const sorted = elements.toSorted((a, b) => b.dataset.score - a.dataset.score);
sorted.forEach((el, i) => applyTransform(el, elements[i]));
}
/**
* Recalculate layout positions and reapply current score-based transforms.
*/
export function refreshLayout(elements) {
getOriginalLocations(elements);
sort(elements);
}
/**
* One animation cycle: new scores, new sort.
*/
export function cycle(elements) {
randomizeScores(elements);
sort(elements);
}