Drawing on HTML Canvas

Drawing on the canvas with JavaScript

All drawing on HTML canvases must be done using JavaScript:

Example

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
</script>

Try it yourself

Step 1: Find the Canvas element

Firstly, you must find the <canvas> element.

This is done by using the HTML DOM method getElementById():

const canvas = document.getElementById("myCanvas");

Step 2: Create the drawing object

Secondly, you need a drawing object for the canvas.

getContext() is an embedded HTML object that provides properties and methods for drawing:

const ctx = canvas.getContext("2d");

Step 3: Draw on the canvas

Finally, you can draw on the canvas.

Set the fill style of the drawing object to red:

ctx.fillStyle = "#FF0000";

The fillStyle property can be a CSS color, gradient, or pattern. The default fillStyle is black.

The fillRect(x, y, width, height) method draws a rectangle on the canvas, filled with a fill style:

ctx.fillRect(0, 0, 150, 75);

See also:

Complete Canvas Reference Manual of CodeW3C.com