Convert Text to Image using canvas

With using canvas we can export image with dynamic text. Let see example below.

HTML code

<h2>Text</h2>
<div id="contentToWrite1" style="border: solid 1px gray; padding: 5px;">
first line
</div>
<br />
<br />
<div id="contentToWrite2" style="border: solid 1px gray; padding: 5px;">
second line
</div>
<h2>Canvas</h2>
<canvas id="canvas" width="200" height="200" style="border: solid 1px gray;">
</canvas>
<br />
<h2>Exported Image</h2>
<img id="exportedImage" width="200" height="200" src="#" />
<br />
<input type="button" name="name" value="export canvas to image" onclick="exportImage();" />

JavaScript code

window.onload = function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.font = "20px Georgia";
var ele = document.getElementById("contentToWrite1");
var ele1 = document.getElementById("contentToWrite2");
if (ele.textContent) {
// for firefox
context.fillText(ele.textContent, 10, 90);
context.fillText(ele1.textContent, 10, 110);
} else {
// for other browser
context.fillText(ele.innerText, 10, 90);
context.fillText(ele1.innerText, 10, 110);
}
}
function exportImage() {
var img = document.getElementById("exportedImage");
img.src = canvas.toDataURL('image/png');
}

On windows load function creates object of canvas and context of canvas. We will use different properties and method of context to
render content on canvas.

  • context.font : This property used to set font style to content on canvas.
  • context.fillText(textToWrite,x,y): this method used to render text on canvas.

By using above methods we have rendered content on canvas, looks like below.

Convert Text to Image using canvas

When we click on button export ‘canvas to image’ image will be set to html image element below to canvas.

  • canvas.toDataURL: This is canvas method to render it as image.

Enjoy JavaScript…

Published by

Mandar Badve

Microsoft web, cloud, mobile developer

Leave a Reply

Your email address will not be published. Required fields are marked *