Introduction
The canvas element is used for drawing graphics using JavaScript. Its default size is 300 pixels wide and
150 pixel high. Now we use the canvas element on our page. We write the following code:
- <!DOCTYPE HTML>
- <html>
- <body>
- <canvas></canvas>
- </body>
- </html>
We look at this page in the browser. The canvas will be not visible because by default the canvas area is invisible. So, now we set a border and write the following code
- <!DOCTYPE HTML>
- <html>
- <body>
- <canvas style="border:2px solid #33C5FF;"></canvas>
- </body>
- </html>
Now the canvas area is visible. The page will look
like the below figure:

Adding Graphics in Canvas
- <!DOCTYPE HTML>
- <html>
- <body>
- <canvas id="CAN" style="border:2px solid #33C5FF ;"></canvas>
- <script type="text/javascript">
- var VAR1 = document.getElementById("CAN");
- var VAR2 = VAR1.getContext("2d");
- VAR2.fillRect(10, 10, 100, 90);
- </script>
- </body>
- </html>

The fill style property accepts a hexadecimal color value. We write the following code:
- <!DOCTYPE HTML>
- <html>
- <body>
- <canvas id="CAN" style="border:2px solid #33C5FF ;"></canvas>
- <script type="text/javascript">
- var VAR1 = document.getElementById("CAN");
- var VAR2 = VAR1.getContext("2d");
- VAR2.fillStyle = "#E0D5DD";
- VAR2.fillRect(10, 10, 100, 90);
- </script>
- </body>
- </html>
We run this code. The page will look like the below figure:

We can draw a custom shape also. We start it with beginpath() then we draw our custom shape and finish it with closepath(). Like the following code:
We run this code. The page will look like the below figure:
We can also set a shadow to the shape of a canvas element by assigning a color value to the property - shadowColor. Like the following code:
- <!doctype html><html><body><canvas id="CAN" style="border:2px solid #33C5FF ;"></canvas><script type="text/javascript">
- var VAR1 = document.getElementById("CAN");
- var VAR2 = VAR1.getContext("2d");
- VAR2.fillStyle = "#807C58";
- VAR2.strokeStyle = "#f00";
- VAR2.lineWidth = 6;
- VAR2.beginPath();
- VAR2.moveTo(20, 20);
- VAR2.lineTo(120, 60);
- VAR2.lineTo(160, 90);
- VAR2.lineTo(80, 120);
- VAR2.lineTo(20, 20);
- VAR2.fill();
- VAR2.stroke();
- VAR2.closePath();
- </script></body></html>

- <!doctype html><html><body><canvas id="CAN" style="border:2px solid #33C5FF ;"></canvas><script type="text/javascript">
- var VAR1 = document.getElementById("CAN");
- var VAR2 = VAR1.getContext("2d");
- VAR2.shadowOffsetX = 10;
- VAR2.shadowOffsetY = 12;
- VAR2.shadowBlur = 6;
- VAR2.fillStyle = "#807C58";
- VAR2.shadowColor = "#7B51C4";
- VAR2.beginPath();
- VAR2.moveTo(20, 20);
- VAR2.lineTo(120, 60);
- VAR2.lineTo(160, 90);
- VAR2.lineTo(80, 120);
- VAR2.lineTo(20, 20);
- VAR2.fill();
- VAR2.stroke();
- VAR2.closePath();
- </script></body></html>
Join the conversation! Your thoughts help the community grow.