How to Draw a rectangle with HTML5 Canvas

In this article I have described the way to draw different shape with the help of Canvas element in HTML5.
  • 2104

Use of <canvas> element in HTML5

The canvas element is used to create native interactivity and animation for web pages

Lets draw a Rectangle

  • As we know that Canvas element always use with JavaScript because canvas element has no drawing capability itself.
  • So we have to use JavaScript code for drawing the rectangle.
  • Within the JavaScript function we have to create two variable like -

<script type="text/javascript">

    function rectangle() {

        var canvas = document.getElementById('cnv');

        var canvas1 = canvas.getContext('2d');

        canvas1.fillStyle = "rgba(100, 200, 0, 1)";

        canvas1.fillRect(30, 30, 75, 70);

    }

</script>

 

These variables are used to access the canvas element from JavaScript Code. Then create rectangle object and fill it with a color.

 

Hence the final code looks like

 

<!DOCTYPE html>

<html>

<head>

<title>Example of canvas</title>

<script type="text/javascript">

    function rectangle() {

        var canvas = document.getElementById('cnv');

        var canvas1 = canvas.getContext('2d');

        canvas1.fillStyle = "rgba(100, 400, 0, 4)";

        canvas1.fillRect(0,0, 85, 80);

    }

</script>

</head>

<body onload="rectangle()">

<h1>Example of Canvas</h1>

<canvas id="cnv" width="200" height="800">

</canvas>

</body>

</html>

 

OUTPUT

 

rect.gif

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.