Skip to content

@fcalderan /silhouette-canvas
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
How to silhouette an image using canvas
/* 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
Something went wrong with that request. Please try again.