Canvas- Use Writing Features to Draw Texts

Written by @m_k_amin 17 June 2013

It is common to use texts within the graphics. HTML5 Canvas has feature to write texts in different formats and fonts. You can set the text alignment and its baseline position, fit a text to a specified width, change font size and font styles and etc. The following codes show how HTML5 Canvas text features works within the web pages. Enjoy!

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.html5freecode.com coded by: Kerixa Inc. -->
<canvas id="myCanvas" width="400" height="250"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')
 	ctx.fillStyle= "brown"
 	ctx.strokeStyle= "darkgreen"
 	
   	ctx.font= "16pt serif"
    ctx.fillText('Serif-16', 10, 20)
	
	ctx.font= "italic 16pt Tahoma"
    ctx.fillText('Tahamoa-it-Fill', 220, 20)
    ctx.strokeText('Tahamoa-it-Stroke', 10, 60)
    ctx.fillText('Tahamoa-it-Compressed', 220, 60, 100)
    
	ctx.font= "oblique lighter 18pt Courier New"
    ctx.fillText('Courier-New-Oblique', 10, 105)
    var w= ctx.measureText('Courier-New-Oblique').width
    ctx.fillText('This text is fitted with the above text.', 10, 130, w)
    
	ctx.beginPath()
	ctx.moveTo(150, 170)
	ctx.lineTo(150, 220)
	ctx.moveTo(20, 180)
	ctx.lineTo(260, 180)
	ctx.moveTo(20, 220)
	ctx.lineTo(260, 220)
    ctx.strokeStyle= "blue"
    ctx.stroke()


 	ctx.font= "italic bold 16pt Arial"
 	ctx.textBaseline= 'middle'
	ctx.textAlign= 'right'
    ctx.fillText('Right-Middle', 150, 180)
 	ctx.textBaseline= 'bottom'
	ctx.textAlign= 'center'
    ctx.fillText('Center-Bottom', 150, 220)    
</script>
<div style="text-align: left"><font face="Tahoma"><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='https://www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Afzal, FOTPU
advertisement 2