Step 2
Let's draw on the canvas! Copy the following code to script.js
and load the index.html
file in your favorite browser (Chrome is recommended) to see the outcome.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 40, 50, 50); // x, y, width, height
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
The fist two lines gets hold of the <canvas>
element and creates the ctx
variable to store the 2D rendering context — the actual tool we can use to paint on the Canvas.
The instructions that followed draw a rectangle on canvas with the specified coordinates and fill color.
The canvas is a coordinate space where origin is the top left corner.