HTML Canvas Text






<!--
main_leaderboard, all: [728,90][970,90][320,50][468,60]
-->



HTML Canvas Text



❮ Previous
Next ❯



Drawing Text on the 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 (no fill)




Using fillText()



Example


Set font to 30px "Arial" and write a filled text on the canvas:



Your browser does not support the HTML5 canvas tag.

var c=document.getElementById("myCanvas2");
var canvOK=1;
try {c.getContext("2d");}
catch (er) {canvOK=0;}
if (canvOK==1)
{
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("Hello World",10,50);
}

JavaScript:



var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);

Try it Yourself »



Using strokeText()



Example


Set font to 30px "Arial" and write a text, with no fill, on the canvas:



Your browser does not support the HTML5 canvas tag.

var c=document.getElementById("myCanvas1");
var canvOK=1;
try {c.getContext("2d");}
catch (er) {canvOK=0;}
if (canvOK==1)
{
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.strokeText("Hello World",10,50);
}

JavaScript:



var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);

Try it Yourself »






<!--
mid_content, all: [300,250][336,280][728,90][970,250][970,90][320,50][468,60]
-->





Add Color and Center Text



Example


Set font to 30px "Comic Sans MS" and write a filled red text in the center of the canvas:



Your browser does not support the HTML5 canvas tag.

var c=document.getElementById("myCanvas3");
var canvOK=1;
try {c.getContext("2d");}
catch (er) {canvOK=0;}
if (canvOK==1)
{
var ctx=c.getContext("2d");
ctx.font="30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", c.width/2, c.height/2);
}

JavaScript:



var
canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);


Try it Yourself »




❮ Previous
Next ❯

Popular posts from this blog

How to check contact read email or not when send email to Individual?

Bahrain

Postfix configuration issue with fips on centos 7; mailgun relay