Created
November 8, 2023 16:55
-
-
Save annibal/17a06289b27febaac4642f10c9c2fa18 to your computer and use it in GitHub Desktop.
Fn to create dots when clicking an element, Fn helper to convert these to scaled, compact array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* const */ dotsMadeStoreArr = []; | |
function attachOnClickMakeDotsListener(elm) { | |
function onClickMakeDotsListener(evt) { | |
onClickMakeDots(evt); | |
} | |
elm.addEventListener("click", onClickMakeDotsListener); | |
return function detachOnClickMakeDotsListener() { | |
elm.removeEventListener("click", onClickMakeDotsListener); | |
} | |
} | |
function onClickMakeDots(e) { | |
const x = e.offsetX / e.target.offsetWidth; | |
const y = e.offsetY / e.target.offsetHeight; | |
if (dotsMadeStoreArr != null && dotsMadeStoreArr instanceof Array) { | |
dotsMadeStoreArr.push([x,y]) | |
} | |
const elm = document.createElement("div") | |
elm.style.position = "absolute" | |
elm.style.width = "4px" | |
elm.style.height = "4px" | |
elm.style.backgroundColor = "red"; | |
elm.style.borderRadius = "20px"; | |
elm.style.left = (x * 100).toFixed(4) + "%"; | |
elm.style.top = (y * 100).toFixed(4) + "%"; | |
console.log(`Created Dot at left=${elm.style.left} top=${elm.style.top}`) | |
e.target.appendChild(elm); | |
} | |
/** | |
* getScale | |
* Creates an scaling function based on two ranges | |
* | |
* @param from [number, number] : the domain of the value you will pass as input | |
* @param to [number, number] : the corresponding range it should output | |
* @returns (number) => number : the scaling function | |
*/ | |
function getScale(from, to) { | |
return function _scale(value) { | |
return (value - from[0]) * (to[1] - to[0]) / (from[1] - from[0]) + to[0]; | |
} | |
} | |
/** | |
* tupleToString | |
* Receive an number tuple, scale, parse decimals and return it as compact string | |
* | |
* @param tupleArr Array : like [ [number, number], [number, number] ] | |
* @param decimals number : how many decimals to keep (default 0) | |
* @param scaleFn (number) => number : function to transform the values | |
* @returns String : should look like "[[-4,8],[15,16],[23,42]]" | |
*/ | |
function tupleToString(tupleArr, decimals = 0, scaleFn = (x) => x) { | |
return '[' + tupleArr | |
.map((x) => [ | |
scaleFn(x[0]).toFixed(decimals), | |
scaleFn(x[1]).toFixed(decimals), | |
]) | |
.map(x => `[${x[0]},${x[1]}]`) | |
.join(',') | |
+ ']'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment