HTML5 Game - Getting a Canvas Context

Introduction

To draw on a canvas element, get a context object, which is an object that exposes drawing functions for a particular style of graphics.

We will be working with the 2d context, which is used to perform two-dimensional operations.

We get a context through the object that represents the canvas element in the DOM.

This object, HTMLCanvasElement is described in the following table.

Member Description Returns
height Corresponds to the height attribute number
width Corresponds to the width attributenumber
getContext(<context>) Returns a drawing context for the canvas object

The key method is getContext.

We use it to get the two-dimensional context object by passing the 2d argument to the method.

Once we have the context, we can begin drawing.

The following code provides a demonstration.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: medium double black; margin: 4px}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="100">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillRect(10, 10, 50, 50);
        </script>
    </body>
</html>// w  w  w.  j a  va  2 s .  com

Related Topic