title
A prototype
Pick a color:
Background color = closest from array:
let pick = document.getElementById('pick') let result = document.body let colors = [ {name: "black",hex: "#000000"}, {name: "blue", hex: "#0000ff"}, {name: "cyan", hex: "#00ffff"}, {name: "gold", hex: "#ffd700"}, {name: "gray", hex: "#808080"}, {name: "red", hex: "#FF0000"}, {name: "lime", hex: "#00ff00"}, {name: "pink", hex: "#ffc0cb"} ] change('#00AD34') for (var i = 0; i < colors.length; i++) { let d = document.createElement('div') d.setAttribute('style', 'background: '+colors[i].hex+'; width:20px; height:20px; display:inline-block; border-radius:20px;') document.body.appendChild(d) } function change(val){ let closest = getClosestColor(val) result.style.backgroundColor = closest } function getClosestColor(hex){ let stats = [] for (var i = 0; i < colors.length; i++) { let color = {} color.hex = colors[i].hex color.score = hexColorDelta(colors[i].hex, hex) stats.push(color) } stats = stats.sort((a,b) => b.score - a.score ) console.log(stats) let bestScore = stats[0].hex return bestScore } function hexColorDelta(hex1, hex2) { hex1 = hex1.replace("#","") hex2 = hex2.replace("#","") var r1 = parseInt(hex1.substring(0, 2), 16); var g1 = parseInt(hex1.substring(2, 4), 16); var b1 = parseInt(hex1.substring(4, 6), 16); // get red/green/blue int values of hex2 var r2 = parseInt(hex2.substring(0, 2), 16); var g2 = parseInt(hex2.substring(2, 4), 16); var b2 = parseInt(hex2.substring(4, 6), 16); // calculate differences between reds, greens and blues var r = 255 - Math.abs(r1 - r2); var g = 255 - Math.abs(g1 - g2); var b = 255 - Math.abs(b1 - b2); // limit differences between 0 and 1 r /= 255; g /= 255; b /= 255; // 0 means opposit colors, 1 means same colors return (r + g + b) / 3; }
snap
save
new
fork
download
html
css
js
output
gallery
config
➚ link to output
➚ snap player
font size
live reload
snap mode
layout
⤷ switch
★ info and code