Javascript函数将颜色名称转换为十六进制代码是否有内置函数可以将颜色按名称转换为十六进制表示形式?就像我想通过'白'并接收'#FFFFFF'一样。如果是我自己,我真的想避免全部编码:)
3 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
这将以RGB形式呈现给您 - 您应该能够非常轻松地进行十六进制转换。
d = document.createElement("div");
d.style.color = "white";
document.body.appendChild(d)
//Color in RGB
window.getComputedStyle(d).color
并非所有浏览器都支持Get Computed样式。
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
我已经清理了一下,并做了一个要点和演示。基本方法保持不变。
“向DOM添加元素并检查其ComputedStyle”方法对我来说似乎有点复杂 - 你需要添加它并检查它并记得删除它并且你只是为了计算颜色而改变DOM并且它会导致它回流?所以这是一个基于临时(并且从未渲染)的解决方案<canvas>:
function colorToRGBA(color) {
// Returns the color as an array of [r, g, b, a] -- all range from 0 - 255
// color must be a valid canvas fillStyle. This will cover most anything
// you'd want to use.
// Examples:
// colorToRGBA('red') # [255, 0, 0, 255]
// colorToRGBA('#f00') # [255, 0, 0, 255]
var cvs, ctx;
cvs = document.createElement('canvas');
cvs.height = 1;
cvs.width = 1;
ctx = cvs.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
return ctx.getImageData(0, 0, 1, 1).data;}function byteToHex(num) {
// Turns a number (0-255) into a 2-character hex number (00-ff)
return ('0'+num.toString(16)).slice(-2);}function colorToHex(color) {
// Convert any CSS color to a hex representation
// Examples:
// colorToHex('red') # '#ff0000'
// colorToHex('rgb(255, 0, 0)') # '#ff0000'
var rgba, hex;
rgba = colorToRGBA(color);
hex = [0,1,2].map(
function(idx) { return byteToHex(rgba[idx]); }
).join('');
return "#"+hex;}请注意,这允许您使用任何有效的画布fillStyle,因此如果您想从图像中提取1像素图案,它也会告诉您颜色。
我已经在IE,Chrome,Safari和Firefox的合理现代版本中对此进行了测试。
添加回答
举报
0/150
提交
取消
