我正在对作为按钮背景图像的图标进行颜色屏蔽。下面的代码适用于图像,但不适用于背景图像。请帮忙!!
IconMasking.js:
函数 tintImage(imgElement, tintColor) {
debugger;
var imgsrc = $(".ui-icon-group").css("background-image");
imgsrc = imgsrc.replace("url(http://localhost:42699", "");
imgsrc = imgsrc.replace(")", "");
imgElement.onload = function () {
house.width = 64;
house.height = 42;
ctxHouse.drawImage(imgElement, 0, 0);
}
imgElement.src = imgsrc;
debugger;
// create hidden canvas (using image dimensions)
var canvas = document.createElement("canvas");
canvas.width = 64;
canvas.height = 42;
debugger;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElement, 0, 0);
var map = ctx.getImageData(0, 0, 320, 240);
var imdata = map.data;
// convert image to grayscale
var r, g, b, avg;
for (var p = 0, len = imdata.length; p < len; p += 4) {
r = imdata[p]
g = imdata[p + 1];
b = imdata[p + 2];
avg = Math.floor((r + g + b) / 3);
imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
}
ctx.putImageData(map, 0, 0);
// overlay filled rectangle using lighter composition
ctx.globalCompositeOperation = "source-atop";
// ctx.globalAlpha = 0.5;
ctx.fillStyle = tintColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// replace image source with canvas data
imgElement.src = canvas.toDataURL();
}
function getStyle(x, styleProp) {
debugger;
if (x.currentStyle) var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
return y;
}
/// some buttons for testing the demo
var bluBtt = document.createElement("button");
bluBtt.appendChild(document.createTextNode("Blue"));
var bgImg = new Image();
bluBtt.onclick = function () {
tintImage(
bgImg,
"#000055"
);
}
document.body.appendChild(bluBtt);
CSS :
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js" type="text/javascript"></script>
<style type="text/css">
.ui-icon-group
{
background-image: url('Images/GroupGray.png');
background-repeat: no-repeat;
}
</style>
HTML :
<div>
<a href="#" data-role="button" data-icon="group" id="dlt">Delete</a>
<script src="Script/IconMasking.js" type="text/javascript"></script>
<br />
</div>