A JavaScript Map stores associations between keys and values so a value can be retrieved by its key. In a Canvas interaction layer, a color key identifies the node drawn with that color. section 15.4
Use a Map to connect hidden Canvas colors with visible visualization nodes:
- Create a Map for node colors. section 15.4
- Generate a color and check whether it already exists with get(). section 15.4
- Store the color and node together with set(). section 15.4
- Retrieve the node after getImageData() returns the color under the pointer. section 15.4
Listing 15.15 Giving a unique color to each node (Paintings.svelte)
<script>
...
let canvasElement;
let context;
let hiddenCanvasElement;
let hiddenContext;
onMount(() => {
...
});
const nodesColors = new Map(); #1
const generateColor = () => { #2
let colorArray = [];
for (let i = 0; i < 3; i++) {
const randomNumber = Math.floor(Math.random()
* 255);
colorArray.push(randomNumber);
}
return colorArray;
};
const addNodeColor = (node) => {
let isNewGeneratedColor = false;
while (!isNewGeneratedColor) {
const colorArray = generateColor(); #3
const colorRGB = `rgb(${colorArray.join(",")})`;
if (!nodesColors.get(colorRGB)) { #4
nodesColors.set(colorRGB, node);
isNewGeneratedColor = true;
return colorRGB;
}
}
};
const handleSimulationEnd = () => {
nodes.forEach((node) => {
...
const color = addNodeColor(node); #5
hiddenContext.fillStyle = color;
hiddenContext.strokeStyle = color;
hiddenContext.beginPath(); #6
hiddenContext.arc(
node.x,
node.y,
node.area_cm2
? Math.sqrt(paintingAreaScale(node.area_cm2)
/ Math.PI)
: paintingDefaultRadius,
0,
2 * Math.PI
); #7
hiddenContext.fill();
hiddenContext.stroke();
});
};
...
</script>
Inspect the complete color-to-node Map implementation, including collision checking and insertion. section 15.4









































