Created
May 2, 2011 07:40
-
-
Save fcalderan/951273 to your computer and use it in GitHub Desktop.
How to silhouette an image using canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* with this snippet you can create a raw silhouette of an image, it works transforming | |
non-white pixels (with a small tolerance) into black pixels */ | |
<img id="canvassource" src="your-image-300x300.jpg" /> | |
<canvas id="area" width="300" height="300"></canvas> | |
<script> | |
window.onload = function() { | |
var canvas = document.getElementById("area"); | |
var context = canvas.getContext("2d"); | |
var image = document.getElementById("canvassource"); | |
context.drawImage(image, 0, 0); | |
var imgd = context.getImageData(0, 0, 300, 300); | |
var pix = imgd.data; | |
var blackpixel = 0; | |
for (var i = 0, n = pix.length; i < n; i += 4) { | |
//console.log(pix[i], pix[i+1], pix[i+2]); | |
if (i > 3) { | |
if ((Math.abs(pix[i-3] - pix[i]) > 10) && | |
(Math.abs(pix[i-2] - pix[i+1]) > 10) && | |
(Math.abs(pix[i-1] - pix[i+2]) > 10) | |
) { | |
pix[i ] = blackpixel; | |
pix[i+1] = blackpixel; | |
pix[i+2] = blackpixel; | |
} | |
} | |
else { | |
if (pix[i] < 250 && pix[i+1] < 250 && pix[i+2] < 250) { | |
pix[i ] = blackpixel; | |
pix[i+1] = blackpixel; | |
pix[i+2] = blackpixel; | |
} | |
} | |
} | |
context.putImageData(imgd, 0, 0); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment