<h1>Generate P3 Color Variations from RGB Hex Values</h1>
Parse an existing code block of hex RGB custom properties in JS on Codepen, assuming lines end with `#aabbcc;` notation, to generate <span class="example">P3 variations</span> as <a href="https://dev.to/ingosteinke/generate-p3-color-variations-from-rgb-hex-values-3fgo" target="_blank">explained in Ingo Steinke's blog post</a>:
<form>
<textarea id="colorsInput">
--brand-orange-html: #f26600;
--fresh-blue: #6440fa;
.example {
color: #012345;
background-color: #fedcba;
}
</textarea>
<textarea id="colorsOutput"></textarea>
<button type="button" onClick="generateP3Approximation()">generate P3 approximations</button></form>
#colorsInput,
#colorsOutput {
height: 180px;
width: 700px;
max-width: 100%;
max-height: 40%;
}
#colorsInput {
height: 120px;
}
.example {
color: #017d63;
color: color(display-p3 0.39 0.39 0.39);
}
const generateP3Approximation = function() {
let output = '';
let textareaInput = document.getElementById('colorsInput');
let textareaOutput = document.getElementById('colorsOutput');
let colorDefinitionsRGB = textareaInput.value.split(/\r?\n/);
colorDefinitionsRGB.forEach((colorDefinition) => {
output += colorDefinition + '\n';
if (!colorDefinition.includes('#') || !colorDefinition.endsWith(';')) {
return;
}
let definitionParts = colorDefinition.split('#');
let hexColor = definitionParts.pop();
let redPart = parseInt(hexColor.substring(0,2), 16);
let greenPart = parseInt(hexColor.substring(2,4), 16);
let bluePart = parseInt(hexColor.substring(4,6), 16);
let propertyPart = (definitionParts[0].split(':'))[0];
colorDefinition = 'color(display-p3';
colorDefinition += ' ' + (redPart / 255).toFixed(2);
colorDefinition += ' ' + (greenPart / 255).toFixed(2);
colorDefinition += ' ' + (bluePart / 255).toFixed(2);
colorDefinition += ')';
output += propertyPart;
if (propertyPart.startsWith('--')) {
output += '-neon';
}
output += ': ' + colorDefinition + ';\n';
});
textareaOutput.value = output;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.