如何在HTML/CSS及Canvas中使用Photoshop API返回的5位RGB色值
解决方法
你拿到的不是异常的5位色值,是Adobe Photoshop API输出的16位深度RGB通道值,每个通道取值范围为032768,而Web端CSS、Canvas支持的是8位通道的0255范围,只需要做一次数值转换即可正常使用。
转换公式
每个通道的Web可用值 = 取整( 原始通道值 / 32768 * 255 )
JavaScript转换代码示例
// 转换PS 16位RGB为Web可用色值 function psRgbToCss(psRgb) { const r = Math.round((psRgb.red / 32768) * 255); const g = Math.round((psRgb.green / 32768) * 255); const b = Math.round((psRgb.blue / 32768) * 255); // 返回css rgb格式字符串 return `rgb(${r}, ${g}, ${b})`; }
使用示例
在Canvas中使用
// 假设你拿到了API返回的fontColor对象 const psFontColor = { "rgb": { "red": 32768, "blue": 32768, "green": 32768 } } const cssColor = psRgbToCss(psFontColor.rgb); // 设置canvas填充色 ctx.fillStyle = cssColor;
在CSS中使用
你可以将转换后的rgb值直接赋值给元素的color、background等样式属性:
document.querySelector('.text-element').style.color = cssColor;
你提供的示例中三个通道都是32768,转换后得到rgb(255,255,255)也就是纯白色,可直接在Web环境中使用。
内容的提问来源于stack exchange,提问作者Anuranjan Pandey
相关产品推荐
相关产品推荐

