以下JavaScript給出了可以用於手動計算不透明度的顏色值的方法:
// caculateTransparentColor(foreground, background, opacity)
var theColor = caculateTransparentColor('#ff0000', '#00ff00', 0.5)
console.log(theColor);
Returns: #808000
代碼:
var COLOR_REGEX = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/;
function colorHexToRGB(htmlColor) {
arrRGB = htmlColor.match(COLOR_REGEX);
if (arrRGB == null) {
alert("Invalid color passed, the color should be in the html format. Example: #ff0033");
}
var red = parseInt(arrRGB[1], 16);
var green = parseInt(arrRGB[2], 16);
var blue = parseInt(arrRGB[3], 16);
return {"r":red, "g":green, "b":blue};
}
function caculateTransparentColor(foregroundColor, backgroundColor, opacity) {
if (opacity < 0.0 || opacity > 1.0) {
alert("assertion, opacity should be between 0 and 1");
}
opacity = opacity * 1.0; // to make it float
var foregroundRGB = colorHexToRGB(foregroundColor);
var backgroundRGB = colorHexToRGB(backgroundColor);
var finalRed = Math.round(backgroundRGB.r * (1-opacity) + foregroundRGB.r * opacity);
var finalGreen = Math.round(backgroundRGB.g * (1-opacity) + foregroundRGB.g * opacity);
var finalBlue = Math.round(backgroundRGB.b * (1-opacity) + foregroundRGB.b * opacity);
return colorRGBToHex(finalRed, finalGreen, finalBlue);
}
function colorRGBToHex(red, green, blue) {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) {
alert("Invalid color value passed. Should be between 0 and 255.");
}
var formatHex = function(value) {
value = value + "";
if (value.length == 1) {
return "0" + value;
}
return value;
}
hexRed = formatHex(red.toString(16));
hexGreen = formatHex(green.toString(16));
hexBlue = formatHex(blue.toString(16));
return "#" + hexRed + hexGreen + hexBlue;
}
謝謝! http://jsbin.com/OxEPEqo/2/edit - 我需要相反的,這是第二組輸入。 – Langdon 2013-08-28 20:02:36
「caculateTransparentColor」方法似乎有前後翻轉的情況。它是'前景*不透明',而不是'前景*(1 - 不透明)'。提交編輯。 – 2014-05-05 19:06:40