html tutorial - rect() Method in HTML5 Canvas - html5 - html code - html form



Rect method in html5 canvas

Learn html - html tutorial - Rect method in html5 canvas - html examples - html programs

  • The rect() is a method of <canvas> element.
  • This method is used to create a rectangle in the canvas.
  • It has four parameters they are x, y, width and height.

Syntax for rect() Method in HTML5 Canvas:

context.rect(x,y,width,height);

Parameter values for rect() Method in HTML5 Canvas:

Value Description
x The x axis coordinate of the rectangle starting point.
y The y axis coordinate of the rectangle starting point.
width It is used to set a width for the rectangle. .
height It is used to set a height for the rectangle.

Sample Coding for rect() Method in HTML5 Canvas:

Tryit<!DOCTYPE html>
<html>
    <head>
      <title>Wikitechy HTML Canvas rect()</title>
    </head>
    <body>
        <h2>HTML Canvas rect with example</h2>
        <canvas id="myCanvas" width="370" height="200" 
        style="border:1px solid blue;">
        </canvas>
        <script>
        var a = document.getElementById("myCanvas");
        var context = a.getContext("2d");
        context.rect(90, 50, 170, 100);
        context.strokeStyle="green";
        context.stroke();
        </script>
    </body>
</html>

Code Explanation for rect() Method in HTML5 Canvas:

rect() method in HTML5 canvas Code Explanation

  1. ”wikitechyCanvas” is used to define the id attribute value for canvas element.
  2. The getElementById(); method is used to get the element that has the id attributes value as “wikitechyCanvas”.
  3. a.getContext(“2d”) method is returns a two-dimensional drawing context on the canvas
  4. rect() method is used to drawing a rectangle in the canvas.
  5. strokeStyle is used to change the color of the rectangle outline as a green.
  6. stroke method is used to draw a path on the canvas.

Output for rect() Method in HTML5 Canvas:

rect() method in HTML5 canvas Output

  1. The canvas rectangle with blue border.
  2. The green color rectangle shows that a rectangle drawn by using rect() method.

Browser Support for rect() Method in HTML5 Canvas:

Yes 9.0 Yes Yes Yes

Tips and Notes

  • The stroke or fill method is used to draw a rectangle on the canvas.
  • The strokeStyle property in canvas is used to change the color of the rectangle outline.

Related Searches to rect() Method in HTML5 Canvas