admin管理员组文章数量:1293319
I found a RGB to hex converter and I'm trying to make a RGBA to hex converter. The original rgb2hex
function works but the new rgba2hex
function does not. What am I doing wrong? The rgba function is returning gba, no r.
// convert RGB color data to hex
function rgb2hex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color ponent";
return ((r << 16) | (g << 8) | b).toString(16);
}
// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color ponent";
return ((r << 32) | (g << 16) | (b << 8) | a).toString(16);
}
Example:
alert(rgb2hex(255, 155, 055));
alert(rgba2hex(255, 155, 055, 255));
Current output: ff9b2d
and 9b2dff
Expected output:ff9b2d
and ff9b2dff
I found a RGB to hex converter and I'm trying to make a RGBA to hex converter. The original rgb2hex
function works but the new rgba2hex
function does not. What am I doing wrong? The rgba function is returning gba, no r.
// convert RGB color data to hex
function rgb2hex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color ponent";
return ((r << 16) | (g << 8) | b).toString(16);
}
// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color ponent";
return ((r << 32) | (g << 16) | (b << 8) | a).toString(16);
}
Example:
alert(rgb2hex(255, 155, 055));
alert(rgba2hex(255, 155, 055, 255));
Current output: ff9b2d
and 9b2dff
Expected output:ff9b2d
and ff9b2dff
2 Answers
Reset to default 8Your issue is that bitwise math in JavaScript caps out at 31 bits, so you can't quite do this as is. You need to use normal math ops, not bitwise ops:
// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color ponent";
return (256 + r).toString(16).substr(1) +((1 << 24) + (g << 16) | (b << 8) | a).toString(16).substr(1);
}
Also fixed an issue with the original algorithm where if the first ponent is < 10, the output doesn't have enough digits.
Anyway, this won't work anyway... #ff9b2dff
isn't a valid color, but you may not care?
RGB to HEX
rgb(0 255 94)
rgb(0, 255, 94)
RGBA to HEX
rgba(255,25,2,0.5)
rgba(255 25 2 / 0.5)
rgba(50%,30%,10%,0.5)
rgba(50%,30%,10%,50%)
rgba(50% 30% 10% / 0.5)
rgba(50% 30% 10% / 50%)
DEMO - CODEPEN.IO
本文标签: javascript shifting issue (rgb and rgba to hex)Stack Overflow
版权声明:本文标题:javascript shifting issue (rgb and rgba to hex) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741576151a2386293.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论