HTML5 canvas text effects.

The <canvas> tag is mainly used to draw and manipulate graphics. But sometimes you may need to draw text in canvas. This text is not normal in the sense that it cannot be selected using mouse. It is like an image drawn on the canvas.

 

In the example codes you can see how you can easily create cool text effects in html5 canvas.

The html code below draws plain text in canvas. You can copy the code and paste it into a blank html document. The <canvas> tag inside the <body> is 600px wide and 500px high.

The fillText method of the 2d rendering context draws the text. It takes four parameters. First parameter is the text(string), second and third paramaters are the X and Y coordinates from where drawing starts, and the fourth parameter(optional) is the maximum width(in float) of the text you want to draw.

 

<!DOCTYPE html>

<html>
<head>
    <title>Text effects in html5 canvas | Qoncious.com</title>
</head>

<body>

<canvas id="canvas" width="600" height="500">
<p> No canvas support! </p>
</canvas>


<script type="text/javascript">
window.onload = function()
{
    var canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');
    
    var text = "Qoncious.com";
    
    context.font = "60px Arial";
    context.fillText(text, 100, 200);
}
</script>

</body>
</html>

 

When this html document is opened in a modern browser, it will look something like the image below.

canvas text plain

 

Canvas Italic text: You can make the text italic by specifying it in the context.font property.

 

context.font = "italic 60px Arial";

context.fillText(text, 100, 200);

 

canvas text italic

 

Canvas text with shadow:

 

context.font = "italic 60px Arial";
context.shadowBlur = 30;
context.shadowColor = "rgb(90, 90, 0)";
context.fillText(text, 100, 200);

 

canvas text shadow

 

Canvas text shadow with offest:

 

context.font = "italic 60px Arial";


context.shadowBlur = 10;
context.shadowColor = "rgb(90, 90, 0)";

context.shadowOffsetX = 8;
context.shadowOffsetY = 8;
context.fillText(text, 100, 200);

 

canvas text shadow offest

 

Canvas colored text: Using fillStyle you can change the color of the text.

 

context.font = "italic 60px Arial";
context.shadowBlur = 30;
context.shadowColor = "rgb(90, 90, 0)";

context.fillStyle = "#ff0000";
context.fillText(text, 100, 200);

 

canvas text colored

 

Canvas stroked text: You can make the text stroked by replacing the fillText method with the strokeText method.

 

context.font = "italic 60px Arial";
context.shadowBlur = 30;
context.shadowColor = "rgb(90, 90, 0)";

context.strokeStyle = "#ff0099";
context.strokeText(text, 100, 200);

 

canvas text stroked

McAfee APAC


You might want to contribute to Qoncious.com:




Latest Videos