Skip to content

Instantly share code, notes, and snippets.

@JanMikes
Last active August 29, 2015 13:57
Show Gist options
  • Save JanMikes/9351777 to your computer and use it in GitHub Desktop.
Save JanMikes/9351777 to your computer and use it in GitHub Desktop.
Very simple jquery script, that adds grayscale filter to your images with class "grayscale". On image hover or parents <a> tag hover image turns into original version using CSS3 transitions. Requires browser with HTML5 support (using 2d canvas).
// jQuerys default .load() is unreliable in WebKit browsers as is said in documentation
$.fn.imageLoad = function(fn){
this.load(fn);
this.each( function() {
if ( this.complete && this.naturalWidth !== 0 ) {
$(this).trigger('load');
}
});
}
$(function(){
$('img.grayscale').imageLoad(function(){
if ($(this).attr("src").indexOf("placehold") == -1) {
$(this).wrap('<span class="grayscale-wrap">');
var $wrapper = $(this).parent(".grayscale-wrap");
var $newImg = $(this).clone().attr("src", grayscale(this)).addClass("gray-img").css("opacity", 0).fadeTo(400, 1, function() {
$(this).removeAttr("style");
});
$wrapper.append($newImg);
}
});
});
// Grayscale w canvas method
function grayscale(imgObj){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
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();
}
.grayscale-wrap {
display: inline-block;
position: relative;
a:hover & {
img.gray-img {
opacity: 0;
}
}
img {
display: inline-block;
.transition(opacity .4s ease);
&.gray-img {
position: absolute;
left: 0;
top: 0;
&:hover {
opacity: 0;
}
}
}
}
<img src="anything.jpg" class="grayscale">
<a href="#">
<img src="anything.jpg" class="grayscale">
</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment