public
Last active

How to silhouette an image using canvas

  • Download Gist
silhouette-canvas
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/* 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>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.