Ang*_*ker 4 html javascript html5 colors mobile-safari
可能重复:
Javascript颜色渐变
我有一个颜色(让我们说黄色)和颜色二(蓝色) - 它们构成一个渐变.
基于0到100的值(0为黄色,100为蓝色),我想表示颜色1和2的混合.
我试图在移动浏览器中进行此操作(具体来说是safari).
有没有办法在javascript中执行此操作?
jfr*_*d00 20
如果你要做的是创建一种在两种其他颜色之间有一定百分比(0-100)的颜色,你可以用这个javascript做到这一点:
function makeGradientColor(color1, color2, percent) {
var newColor = {};
function makeChannel(a, b) {
return(a + Math.round((b-a)*(percent/100)));
}
function makeColorPiece(num) {
num = Math.min(num, 255); // not more than 255
num = Math.max(num, 0); // not less than 0
var str = num.toString(16);
if (str.length < 2) {
str = "0" + str;
}
return(str);
}
newColor.r = makeChannel(color1.r, color2.r);
newColor.g = makeChannel(color1.g, color2.g);
newColor.b = makeChannel(color1.b, color2.b);
newColor.cssColor = "#" +
makeColorPiece(newColor.r) +
makeColorPiece(newColor.g) +
makeColorPiece(newColor.b);
return(newColor);
}
Run Code Online (Sandbox Code Playgroud)
该函数假设梯度是在两个端点颜色的每个r,g和b通道值之间进行线性插值,使得50%梯度值是每个r,g,b值的中点(两种颜色之间的中间值) .一旦可以制作不同类型的渐变(具有不同的插值函数).
要将此结果分配给背景,请使用我添加到返回结果中的CSS颜色值,如下所示:
// sample usage
var yellow = {r:255, g:255, b:0};
var blue = {r:0, g:0, b:255};
var newColor = makeGradientColor(yellow, blue, 79);
element.style.backgroundColor = newColor.cssColor;
Run Code Online (Sandbox Code Playgroud)