Convert Text into Image using JavaScript Canvas

To convert text into image at client side we can utilize HTML5 new canvas element.

We can set background of canvas, write text in different fonts and different color on canvas and then finally can convert the canvas into the data URI using canvas's function toDataURL.

Let us go through the code, comments in the code explains the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Convert Text into Image using JavaScript Canvas</title>
</head>
<body>
    <div id="dummydiv" style="position:absolute; z-index:10px; left: -20px; top:-20px; font-family: Verdana; font-size: 15px;"></div>
    <input name="txtToBePrintedAsImage" type="text" id="txtToBePrintedAsImage" value="Welcome to TechMCQ.com" />
    <input type="button" value="Print" onclick="javascript:print();" />
    <br /><strong>Canvas</strong>
    <canvas id="cnvs" style="width: 20px; height: 20px;" width="20" height="20"></canvas>
    <br /><strong>Final Image:</strong>
    <img id="img" />
    <script>
        function print() {
            var txt = document.getElementById("txtToBePrintedAsImage").value;

            //get the height and width of text using dummydiv
            //we will use these to set the height and width of the canvas
            document.getElementById("dummydiv").innerText = txt;
            var cw = document.getElementById("dummydiv").offsetWidth;
            var ch = document.getElementById("dummydiv").offsetHeight;

            var canvas = document.getElementById("cnvs");
            //set the height and width of canvas
            canvas.style.width = (cw + 10) + "px";
            canvas.style.height = (ch + 10) + "px";
            canvas.width = cw + 10;
            canvas.height = ch + 10;
            var context = canvas.getContext("2d");
            //change the font of the canvas
            context.font = "15px Verdana";
            //change the color to yellow
            context.fillStyle = "yellow";
            //draw the background using yellow color
            context.fillRect(0, 0, cw + 10, ch + 10);
            //change the brush color to black
            context.fillStyle = "black";
            //write text on the canvas
            context.fillText(txt, 5, 16);
            //Get the Data URI of the canvas image
            var dataURL = canvas.toDataURL("image/png");
            //assign the data URI to image element
            document.getElementById("img").src = dataURL;
        }
    </script>
</body>
</html>



Here is the live demo



Canvas
Final Image:


Add Comments :

Login

Register