Draw text on html5 canvas using javascript

How to draw text using HTML5 canvas in javascript with different styles.

 HTML5 Canvas   

Posted: June 29, 2018. | By: mustafa

HTML5 has brought some exciting new features to the HTML llike canvas. Using HTML5 Canvas we can draw text using various fonts, sizes and colors. We can draw either filled or outlined text, either using the fillText, or stokeText respectively. The font and fillStyle properties of the context may be used to control the text font, font size and color.


Canvas html markup


<canvas id="Canvas1" width="400" height="200" ></canvas>


To draw text on a canvas, the most important property and methods are:

font - defines the font properties for the text
fillText(text,x,y) - draws "filled" text on the canvas
strokeText(text,x,y) - draws text on the canvas with outline


The x and y represents the horizontal and vertical position where the text is to be drawn.


var canvas = document.getElementById("myCanvas");

var context = canvas.getContext("2d");

First, get the html canvas 2d context property and then set the font and fillStyle of the canvas object.

fillText() and strokeText() methods.


fillText (text, x, y [,maxWidth]);
strokeText (text, x, y [,maxWidth]);


Complete above code is added in a example html file.





<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.1.min.js" type="text/javascript">

$(document).ready( function () {
var canvas = document.getElementById('Canvas01');
 var ctx = canvas.getContext('2d');
 // Add text to first line
 ctx.font = "37px Verdana";
 ctx.strokeStyle = "#0000FF"; // use strokeStyle to draw outlined text
 ctx.strokeText("HTML5 Canvas", 100, 50);
 // Add text to second line
 ctx.font = "normal 24px Courier";
 ctx.fillStyle = "#00FF21";
 ctx.fillText("Draw Text", 140, 120);
 // Add text to third line
 ctx.font = 'bold 16px Arial';
 ctx.textAlign = 'center';
 ctx.textBaseline = 'middle';
 ctx.fillStyle = 'green'; // a color name or by using rgb/rgba/hex values
 ctx.fillText('Hello World!', 200, 150); // text and position




<canvas id="Canvas01" width="400" height="200" style="border:2px solid #bbb; margin-left:10px; margin-top:10px;"></canvas>



CanvasText.png, Canvas, HTML5, canvas, Draw Text, javascript,

related posts

Back to top