Cross-Browser Grayscale background image
Posted by admin at 8:59 日時 2014/03/31
This is a modified version of a tutorial “Cross-Browser Grayscale image example using CSS3 + JS“.
This original version worked well, but only for actual img objects. If you’d like to apply mouse over grayscale effect for background images, try modify functions.js like this:
if (getInternetExplorerVersion() >= 10){ $('.example ul').imagesLoaded(function(){ $('.example ul li').each(function(){ // get background-image style value var backgroundImage = $(this).css('background-image'); // get background-image src var backgroundImageSrc = backgroundImage.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''); // get grayscale data url var grayScaleImageSrc = grayscaleIE10(backgroundImageSrc); // set color image src to data attribute $(this).data('image-src', backgroundImageSrc); // set grayscale image src to data attribute $(this).data('grayscale-src', grayScaleImageSrc); // change grayscale to default this.style.backgroundImage = "url(" + grayScaleImageSrc + ")"; }).hover(function(){ // change to the color image var src = $(this).data('image-src'); this.style.backgroundImage = "url(" + src + ")"; }, function(){ // change back to the grayscale image var src = $(this).data('grayscale-src'); this.style.backgroundImage = "url(" + src + ")"; }); }); function grayscaleIE10(src){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var imgObj = new Image(); imgObj.src = src; canvas.width = 300; // from your stylesheet canvas.height = 200; // from your stylesheet ctx.clearRect(0, 0, canvas.width, canvas.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(); }; };
マウスオーバーするとグレイスケールの画像がカラーになる、という効果を実装するサンプル。リンク先のチュートリアルの通りにすればimgタグを使っている場合はうまくいくのですが、背景画像の場合、このIE10以降対応の部分が動きません。なのでちょいと変更してみたサンプルです。
Thanks to original blog post and wonderful tutorial!