20 October 2010

How to put, render, write or draw text in canvas tag using drawText function in JavaScript.

HTML:

Create a HTML file and put a canvas tag in it. Give it a size and we are off to write some JavaScript to render the text.
Source code viewer
  1. <canvas id="canvas_text" width="250" height="250"></canvas>
Programming Language: XML

JavaScript:

Of course you have to put JavaScript in script tag. But this example code writes your test in your string in to canvas tag.
Source code viewer
  1. var canvas_text = document.getElementById("canvas_text").getContext("2d");
  2.  
  3. //font = 'size font-family'
  4. canvas_text.font = '20pt Arial';
  5. //fillText(string, x, y)
  6. canvas_text.fillText('Hello, world!', 50, 25);
Programming Language: Javascript
If you play with the parameters you can see how the text changes.