我继承了一个小型 Web 应用程序,该应用程序具有用户可以从下拉列表中选择颜色的功能,然后对图像的一部分进行着色。
着色是通过名为 Pixastic 的 Javascript 库进行的。 .
Pixastic 将图像加载到 Canvas 元素中,使用其 Pixastic coloradjust 处理图像。功能。
就我而言,正在处理的图像是带有黑色/灰色轮廓的透明 PNG。最终结果是只有黑色/灰色轮廓被着色。
但这就是棘手的部分。
Pixastic coloradjust
函数不仅仅采用十六进制或 RGB 颜色。它需要一组调整参数来调整红色、绿色和蓝色 channel 。每个调整值可以是 -1 到 1 之间的十进制数。
coloradjust
函数的工作原理基本上是这样的:
- 令
r
为红色 channel 调整值。 - 多个
r
* 255,令结果为redVal
- 循环图像中的每个像素
- 将
redVal
添加到像素的红色值 (redPixel) - 如果
redVal + redPixel
< 0,则将像素设置为 0 - 如果
redVal + redPixel
> 255,则将像素设置为 255 - 否则,将像素设置为
redVal + redPixel
*对绿色和蓝色 channel 执行相同的操作。
如果有帮助,这里是 coloradjust
function 的实际代码.
我有一个现有颜色和调整值的列表。
我的任务是向应用程序添加一些新颜色,但我完全专注于弄清楚如何计算给定十六进制颜色的 PIxastic 的颜色调整值。
现有的十六进制颜色和调整值之间似乎没有任何相关性,因此我担心现有的调整值是有人手动计算出来的。
以下是现有系统中的一些示例颜色:
- #603314
- 红色调整
-0.1
- 绿色调整
-0.5
- 蓝色调整
-0.3
- 红色调整
- #82bad4
- 红色调整
0.2
- 绿色调整
0.4
- 蓝色调整
0.4
- 红色调整
考虑到上述所有内容,我如何计算出新的十六进制颜色(如 #cc9e3c
)的颜色调整值?
最佳答案
我尝试创建一些函数来返回红色、绿色和蓝色比例,这就是问题描述的方式。然而,我的计算都不符合示例,所以我猜我没有完全理解这个问题。尽管如此...
function redScale(colorInput) {return parseInt(colorInput.substring(1,3),16)/255 * 2 - 1;}
function grnScale(colorInput) {return parseInt(colorInput.substring(3,5),16)/255 * 2 - 1;}
function bluScale(colorInput) {return parseInt(colorInput.substring(5,7),16)/255 * 2 - 1;}
substring 方法从 colorInput 字符串中获取两位十六进制值。获得两位数的十六进制字符串后,我使用 parseInt 将其转换为十进制。将其除以 255,得到 0 到 1 的范围。由于范围从 -1 到 1(长度为 2),因此将其乘以 2(得到 0 到 2 的范围),然后减去 1,得到 -1 到 1 的范围。 */
var colorInput = "#603314";
rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);
document.write("input: " + colorInput + "<br/>red: "+rCS+"<br/>","green: " + gCS + "<br/>" + "blue: " + bCS + "<br/><br/>");
colorInput = "#82bad4";
rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);
document.write("input: " + colorInput + "<br/>red: "+rCS+"<br/>","green: " + gCS + "<br/>" + "blue: " + bCS + "<br/><br/>");
colorInput = "cc9e3c";
rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);
document.write("input: " + colorInput + "<br/>red: "+rCS+"<br/>","green: " + gCS + "<br/>" + "blue: " + bCS);
关于javascript - 尝试从十六进制或 RGB 颜色计算 Pixastic 颜色调整值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947670/