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 attribute | number |
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.
<!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