HTML5 Game - Canvas Canvas Tag

Introduction

HTML5 canvas is an HTML tag that you can embed inside an HTML document to draw graphics with JavaScript.

Here is the base template for all of the 2D HTML5 Canvas recipes for this book:

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> 
<html> 
    <head> 
        <script> 
            window.onload = function(){ 
                let canvas = document.getElementById("myCanvas"); 
                let context = canvas.getContext("2d");
                // draw stuff here 
            }; //from   www.  j  av  a 2  s  . c o  m
        </script> 
    </head> 
    <body> 
        <canvas id="myCanvas" width="500" height="200"> 
        </canvas> 
    </body> 
</html>

Note

The canvas element is embedded inside the body of the HTML document.

It is defined with an id, a width, and a height.

JavaScript uses the id to reference the canvas tag.

The width and height are used to define the size of the drawing area.

Once the canvas tag has been accessed with document.getElementById(), we can then define a 2D context with:

let context = canvas.getContext("2d"); 

Related Topics