Drawing Text in Canvas Using Javascript

Language
This project will teach you how to draw text in canvas using javascript. Let's see the parameters that the filltext method and stroketext method intake.
  1. context.fillText('This is the text!', 20, 60);
  2. context.strokeText('This is the text!', 20, 60);
The first parameter is the string of text, second is the x position, and the third is the y position. You can also maximum width. It is optional. We can also modify the properties of the text. Here's the example:
  1. context.font = "italic bold 32px Tahoma, sans serif";
This is the full code for reference.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style type="text/css">
  5.         #box{
  6.                 width:500px;
  7.                 height:300px;
  8.                 background:#fff;
  9.         }
  10. </style>
  11. <script type="text/javascript">
  12.         function draw_text (){
  13.                 var context = document.getElementById('box').getContext('2d');
  14.                 context.fillStyle = "#71C0F5";
  15.                 context.font = "italic bold 32px Tahoma, sans serif";
  16.                 context.fillText('This is the text!', 20, 60); //First Parameter is the string of text, x position, y position
  17.                 context.textAlign = 'start';//it could be start, end, left, right, center
  18.                 context.textBaseline = 'hanging'; // it could be top, middle, bottom, hanging, alphabetic, ideographic
  19.                 context.lineWidth = 2;//thickness of stroke
  20.                 context.strokeText('This is the text!', 20, 60);
  21.         }
  22.         window.onload = draw_text;
  23. </script>
  24. <title>Drawing Text on Canvas</title>
  25. </head>
  26. <body>
  27.         <canvas id="box"></canvas>
  28. </body>
  29. </html>
Hope you learn from this.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment