Saturday, March 5, 2016

HTML5 - Text

We can write font and set many different properties like:
font, alignment and measure text length

Properties

font - sets the font properties using the same values as CSS
textAlign

  • start
  • end
  • left
  • right
  • center

textBaseline - sets vertical alignment

  • top
  • hanging
  • middle
  • alphabetic
  • ideographic
  • bottom

measureText(text) - measure string and get size back in pixels


Code Snippet
HTML
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
         <script src="script.js"></script>
        <title>Demo HTML5 Text</title>
    </head>
    <body>
        <section id="CanvasSection">
            <canvas id="canvas" width="500" height="300"></canvas>
        </section>
    </body>
</html> 
 
Javascript - script.js

function textdemo() 
{
    var elem = document.getElementById('canvas');
    var canvas = elem.getContext('2d');
 
    canvas.font = "bold 20px segoe UI, sans-serif";
    canvas.textAlign = "start";
    canvas.textBaseline = "bottom";
 
    var message = "Hello Html5!";
    canvas.fillText(message,200,220);
 
    var textSize = canvas.measureText(message);
    canvas.strokeRect(200, 200, textSize.width, 20);
}
addEventListener("load", textdemo);
 
Output