To test our canvas, let's draw a rectangle in the canvas by typing the following code:
<script type="text/javascript"> var canvas = document.getElementById("canvasTest"); //called our canvas by id var canvasElement = canvas.getContext("2d"); // made our canvas 2D canvasElement.fillStyle = "black"; //Filled the canvas black canvasElement.fillRect(10, 10, 50, 50); //created a rectangle </script>
In the script, we declared two JavaScript variables. The canvas
variable is used to hold the content of our canvas using the canvas ID, which we used in our <canvas></canvas>
tags. The canvasElement
variable is used to hold the context of the canvas. We assign black
to fillstyle
so that the rectangle that we want to draw turns black when filled. We used canvasElement.fillRect(x, y, w, h);
for the shape of the rectangle. Where x
is the distance of the rectangle from the x axis; y
is the distance of the rectangle from the y axis; and w
and h
are the width and height of the rectangle, respectively.
The full code is as shown in the following:
<html> <head> <title>Canvas</title> </head> <body> <canvas id="canvasTest" width="200" height="100" style="border:2px solid #000;"> </canvas> <script type="text/javascript"> var canvas = document.getElementById("canvasTest"); //called our canvas by id var canvasElement = canvas.getContext("2d"); // made our canvas 2D canvasElement.fillStyle = "black"; //Filled the canvas black canvasElement.fillRect(10, 10, 50, 50); //created a rectangle </script> </body> </html>
3.138.174.95