Skip to content

Instantly share code, notes, and snippets.

Created June 20, 2011 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1036157 to your computer and use it in GitHub Desktop.
Save anonymous/1036157 to your computer and use it in GitHub Desktop.
B*W to Color
Okie dokie.
https://gist.github.com/1036157
<pre>
&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
&lt;meta charset="utf-8">
&lt;title>untitled&lt;/title>
&lt;style>
/* Setup...not important. */
.img-wrap {
width: 500px;
margin: 100px auto;
position: relative;
cursor: pointer;
}
/* Handles animation of b*w to color */
canvas {
position: absolute;
left: 0;
top: 0;
opacity: 1;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
}
canvas:hover {
opacity: 0;
}
/* If you MUST have IE support */
#cvs-src {
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
}
#cvs-src:hover {
filter: none;
}
&lt;/style>
&lt;/head>
&lt;body>
&lt;div class="img-wrap">
&lt;img id="cvs-src" src="your-image.jpg" />
&lt;canvas width=500 height=500>&lt;/canvas>
&lt;/div>
&lt;script>
(function() {
var supportsCanvas = !!document.createElement('canvas').getContext;
supportsCanvas && (window.onload = greyImages);
function greyImages() {
var ctx = document.getElementsByTagName("canvas")[0].getContext('2d'),
img = document.getElementById("cvs-src"),
imageData, px, length, i = 0,
grey;
ctx.drawImage(img, 0, 0);
// Set 500,500 to the width and height of your image.
imageData = ctx.getImageData(0, 0, 500, 500);
px = imageData.data;
length = px.length;
for ( ; i &lt; length; i+= 4 ) {
grey = red * .3 + green * .59 + blue * .11;
px[i] = px[i+1] = px[i+2] = grey;
}
ctx.putImageData(imageData, 0, 0);
}
})();
&lt;/script>
&lt;/body>
&lt;/html>
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment