如何将灰度jquery插件应用于背景图像?

我想使用jquery-grayscale将图像颜色转换为各自的灰度。 使用它非常简单,识别图像并应用插件:

$('#my-icon').grayscale() 

但是,如果图像在css文件中定义为背景图像,该怎么做呢?

 #my-icon{ background-image:url('../Images/my-icon.png'); } 

谢谢。-

编辑:当然,任何其他方式转换为灰度这些图标也很有用。 任何的想法?

我想你正在使用这个插件 ? 看看代码它似乎只支持图像,所以你要么必须修改它,要么希望别人这样做。

(我知道它是一个旧post,但是为了记录https://stackoverflow.com/questions/7704415/how-to-apply-the-grayscale-jquery-plugin-to-a-background-image/…)如果你想立即从彩色切换到灰度,请检查这个post 。 如果要逐渐切换它们,请使用jquery和canvas。

这是一个基于HTML5灰度图像hover网站的示例代码,因为它们的版本只支持元素,我这个代码使用’background’css规则代替:

HTML:

 

CSS:

 div.gray { width: 300px; height: 00px; opacity: 0; background-image: url(images/yourimage.jpg); } 

JS:

 jQuery(function() { $ = jQuery; // On window load. This waits until images have loaded which is essential $(window).load(function(){ // Fade in images so there isn't a color "pop" document load and then on window load $("div.gray").animate({opacity:1},500); // clone colored image, convert it to grayscale and place the cloned one on top $('div.gray').each(function(){ var div = $(this); var bg = div.css('background-image'); bg = /^url\((['"]?)(.*)\1\)$/.exec(bg); bg = bg ? bg[2] : ""; if(bg) { var el = $("
"); div.append(el); el.addClass('color').css({ "position":"absolute", "z-index":"100", "opacity":"0", "background-image":"url('"+bg+"')" }); div.css('background-image',"url('"+grayscale(bg)+"')"); } }); // Fade image $('div.gray').mouseover(function(){ var div = $(this); div.find('div.color').css({ "width":div.width(), "height":div.height(), "top":div.position().top, "left":div.position().left, }).stop().animate({opacity:1}, 1000); }) $('div.color').mouseout(function(){ $(this).stop().animate({opacity:0}, 1000); }); }); // Grayscale w canvas method function grayscale(src){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var imgObj = new Image(); imgObj.src = src; canvas.width = imgObj.width; canvas.height = imgObj.height; ctx.drawImage(imgObj, 0, 0); var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); for(var y = 0; y < imgPixels.height; y++){ for(var x = 0; x < imgPixels.width; x++){ var i = (y * 4) * imgPixels.width + x * 4; var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL(); } });

“url(https://stackoverflow.com/questions/7704415/how-to-apply-the-grayscale-jquery-plugin-to-a-background-image/...)”解析器是从这个线程获得的。 它不处理任何类型的值,但适用于简单的路径。 您可以修改正则表达式。 如果你需要更多。

您可以在JSBin中看到示例代码: http ://jsbin.com/qusotake/1/edit?html,css,js 但是由于域限制(使用图像)它不起作用。 请下载代码和映像,然后在本地Web服务器中执行。

我之前已经问过这个问题。

由于性能原因,我选择不在客户端将图像转换为灰度。