Skip to content

Instantly share code, notes, and snippets.

@todays-mitsui
Last active February 3, 2025 13:55
Show Gist options
  • Save todays-mitsui/55533d8df763c28aa5a762f824c73e1f to your computer and use it in GitHub Desktop.
Save todays-mitsui/55533d8df763c28aa5a762f824c73e1f to your computer and use it in GitHub Desktop.
色記法を雑に正規化する
/**
* 様々な色記法を rgb()/rgba() 形式に正規化する
*
* style 属性に書いたり読んだりするだけバージョン
*
* @param {string} colorStr
* @returns {string}
*/
function normalize_v1(colorStr) {
const div = document.createElement('div');
div.style.color = colorStr;
return div.style.color;
}
console.assert(normalize_v1('rgb(100, 149, 237)') === 'rgb(100, 149, 237)');
console.assert(normalize_v1('#6495ed') === 'rgb(100, 149, 237)');
console.assert(normalize_v1('hsl(218.54, 79%, 66%)') === 'rgb(100, 149, 237)');
console.assert(normalize_v1('cornflowerblue') === 'rgb(100, 149, 237)',
'<named-color> には未対応');
console.assert(normalize_v1('color(srgb 0.392 0.584 0.929)') === 'rgb(100, 149, 237)',
'color() 関数記法には未対応');
/**
* 様々な色記法を rgb()/rgba() 形式に正規化する
*
* style 属性に書いて getComputedStyle() で読み出すバージョン
*
* @param {string} colorStr
* @returns {string}
*/
function normalize_v2(colorStr) {
const div = document.createElement('div');
document.body.appendChild(div);
div.style.display = 'none';
div.style.color = colorStr;
const computed = getComputedStyle(div).color;
document.body.removeChild(div);
return computed;
}
console.assert(normalize_v2('rgb(100, 149, 237)') === 'rgb(100, 149, 237)');
console.assert(normalize_v2('#6495ed') === 'rgb(100, 149, 237)');
console.assert(normalize_v2('hsl(218.54, 79%, 66%)') === 'rgb(100, 149, 237)');
console.assert(normalize_v2('cornflowerblue') === 'rgb(100, 149, 237)');
console.assert(normalize_v2('color(srgb 0.392 0.584 0.929)') === 'rgb(100, 149, 237)',
'color() 関数記法には未対応');
/**
* 様々な色記法を rgb()/rgba() 形式に正規化する
*
* 1px の canvas を塗って getImageData() で読み出すバージョン
*
* @param {string} colorStr
* @returns {string}
*/
function normalize_v3(colorStr) {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx.fillStyle = colorStr;
ctx.fillRect(0, 0, 1, 1);
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
return a === 255
? `rgb(${r}, ${g}, ${b})`
: `rgba(${r}, ${g}, ${b}, ${a / 255})`;
}
console.assert(normalize_v3('rgb(100, 149, 237)') === 'rgb(100, 149, 237)');
console.assert(normalize_v3('#6495ed') === 'rgb(100, 149, 237)');
console.assert(normalize_v3('hsl(218.54, 79%, 66%)') === 'rgb(100, 149, 237)');
console.assert(normalize_v3('cornflowerblue') === 'rgb(100, 149, 237)');
console.assert(normalize_v3('color(srgb 0.392 0.584 0.929)') === 'rgb(100, 149, 237)');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment