这是一个带有 3 个参数的小函数:data、colorFrom、colorTo(两种颜色都应以十六进制提供)
function changeColInUri(data,colfrom,colto) {
// create fake image to calculate height / width
var img = document.createElement("img");
img.src = data;
img.style.visibility = "hidden";
document.body.appendChild(img);
var canvas = document.createElement("canvas");
canvas.width = img.offsetWidth;
canvas.height = img.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
// remove image
img.parentNode.removeChild(img);
// do actual color replacement
var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
var data = imageData.data;
var rgbfrom = hexToRGB(colfrom);
var rgbto = hexToRGB(colto);
var r,g,b;
for(var x = 0, len = data.length; x < len; x+=4) {
r = data[x];
g = data[x+1];
b = data[x+2];
if((r == rgbfrom.r) &&
(g == rgbfrom.g) &&
(b == rgbfrom.b)) {
data[x] = rgbto.r;
data[x+1] = rgbto.g;
data[x+2] = rgbto.b;
}
}
ctx.putImageData(imageData,0,0);
return canvas.toDataURL();
}
需要一个额外的函数来将十六进制颜色转换为 RGB(正确匹配)
function hexToRGB(hexStr) {
var col = {};
col.r = parseInt(hexStr.substr(1,2),16);
col.g = parseInt(hexStr.substr(3,2),16);
col.b = parseInt(hexStr.substr(5,2),16);
return col;
}
用法是这样的:
changeColInUri(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVR42mNgQALCi7//J4QZcAFiNOM1hJANBA0h1QC83iHFizDJ/dgww/7/LAQNwKUZbkjDfya8YQZXiCqJagilBmAzhLYGYDNsJBhAMD3gS854NS/6vg+fZgDKvmW19S7PRAAAAABJRU5ErkJggg==",
"#13A3F7",
"#ff6400"
);
它将返回一个新数据:image/png;具有交换颜色的 URI,这是最终结果的工作 jsfiddle
http://jsfiddle.net/V5dU2/
(在 Chrome、Firefox 和 IE10 上测试)