Preview the color on hover, lock it by clicking.

This commit is contained in:
Anthony Lieuallen 2022-11-20 19:51:45 -05:00
parent 53f5afab4b
commit 2ac28c5523
1 changed files with 52 additions and 9 deletions

View File

@ -3,8 +3,13 @@
<title>Named Colors Wheel</title>
<style>
body {
font-family: sans-serif;
text-align: center;
}
#swatch {
display: inline-block;
min-width: 5em;
}
</style>
</head>
<body>
@ -227,7 +232,6 @@ voronoi.cells.forEach(cell => {
let [r, g, b] = colors[colorName];
let c = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
// c.setAttribute('style', `fill: );
c.setAttribute('data-color', colorName);
c.setAttribute('mask', 'url(#circle-mask)');
@ -244,21 +248,60 @@ voronoi.cells.forEach(cell => {
svgStyle.insertRule(`[data-color=${colorName}] { fill: ${rgb}; stroke: ${rgb}; }`);
});
function activateColor(el) {
renderPreview(el.getAttribute('data-color'));
// Move the SVG node to the end, so it(s stroke) will draw above all others.
el.parentNode.appendChild(el);
// Force its stroke to be black. (Doing this with CSS doesn't work; the
// hover state is broken by mutating the DOM.)
el.style.stroke = 'black';
}
svg.addEventListener('mouseover', e => {
let el = e.target;
if (el.tagName != 'polygon') return;
if (!el.nextElementSibling) return;
let parent = el.parentElement;
// Move the SVG node to the end, so it(s stroke) will draw above all others.
parent.appendChild(el);
// Force its stroke to be black. (Doing this with CSS doesn't work; the hover
// state is broken by mutating the DOM.)
el.style.stroke = 'black';
if (!previewLocked) {
activateColor(el);
}
});
svg.addEventListener('mouseout', e => {
let el = e.target;
if (el.tagName != 'polygon') return;
// Reset stroke from mouseover.
el.style.stroke = '';
if (!previewLocked) {
renderPreview(null);
// Reset forced stroke from mouseover.
el.removeAttribute('style');
}
});
svg.addEventListener('click', e => {
let el = e.target;
if (el.tagName != 'polygon') return;
// Remove possible forced stroke from previously-locked color.
document.querySelectorAll('polygon[style]').forEach(el => {
el.removeAttribute('style');
});
previewLocked = true;
activateColor(el);
});
let previewLocked = false;
function renderPreview(color) {
if (!color) {
document.getElementById('preview').innerHTML = '';
return;
}
document.getElementById('preview').innerHTML = `
<h1>
${color}
<span id='swatch' style='background-color: ${color};'>&nbsp;</span>
</h1>
`;
}
</script>
<div id="preview"></div>