HTML5 Game - Canvas Drawing text

Introduction

The following code shows how to set font style for text on canvas.

The font property takes a string value in the same way as the font property in CSS.

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Learning the basics of canvas</title>
    <meta charset="utf-8">
    //www  .j  a  v  a 2  s.com
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        let text = "Hello, World!"; // String of text to display
        context.font = "italic 30px serif";// Change the size and font
        context.fillText(text, 40, 40); // Draw the text
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topic