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" "">
<html xmlns="">
    <title>Convert Text into Image using JavaScript Canvas</title>
    <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" />
    <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" />
        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
   = (cw + 10) + "px";
   = (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;

Here is the live demo

Final Image:

Add Comments :

asdsafa 04 Feb 18









uytiuyo /*85-595 06 Dec 17

mkgmfg kmfgkmkfgm 5454 &(=?===

asdf 10 Oct 17