Monday, August 27, 2012

Javascript example code to create a silhouette of an image using the Canvas

The HTML5 Canvas object can be used to do simple image processing tasks such as blurring, sharpening, darkening etc. provided the proper algorithm is written into the Javascript code. This post will provide an example of turning a transparent image such as the sample image on the right into a silhouette.

The code logic is quite straightforward - draw the image onto the canvas, then read each RGBA pixel from the canvas and set the RGB values to zero while keeping the alpha channel values intact.

The following is just the HTML code for laying out the image and button elements.

<!DOCTYPE html>
<html>
<head>
<title>Create Silhouette from an Image using the Canvas</title>
<script type="text/javascript" src="silhouette.js">
</script>
</head>
<body>
<p>
<img id="sourceImg" src="silhouette01.png" />
<img id="silhouetteImg" src="" />
</p>
<p>
<input type="button" value="Create Silhouette" id="createSilhouetteButton" />
</p>

</body>
</html>

The HTML page is rendered in a browser as shown above. 

The following is the Javascript code that converts the source image into a silhouette when the button is clicked.
window.onload = init;
function init() {
    document.getElementById("createSilhouetteButton").onclick = onButtonClick;
}
function onButtonClick(){
    var canvas = document.createElement("canvas");
    var sourceImg = document.getElementById("sourceImg");
    var silhouetteImg = document.getElementById("silhouetteImg");
    var ctx = canvas.getContext('2d');
    canvas.width = sourceImg.width;
    canvas.height = sourceImg.height;
    ctx.drawImage(sourceImg,0,0);
    var imgData = ctx.getImageData(0,0,canvas.width,canvas.height);
    var pix = imgData.data;
    //convert the image into a silhouette
    for (var i=0, n = pix.length; i < n; i+= 4){
        //set red to 0
        pix[i] = 0;
        //set green to 0
        pix[i+1] = 0;
        //set blue to 0
        pix[i+2] = 0;
        //retain the alpha value
        pix[i+3] = pix[i+3];
    }
    ctx.putImageData(imgData,0,0);
    silhouetteImg.src = canvas.toDataURL();
};

When the button is clicked, this resultant silhouette image is created. 

No comments:

Post a Comment