HTML5 Canvas Reference - rect()








The rect() method creates a rectangle.

We have to use the stroke() to draw the outline of the rectangle or use the fill() method to fill the rectangle on the canvas.

Browser compatibility

rect() Yes Yes Yes Yes Yes

JavaScript syntax

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

Parameter Values

Parameter Description
x The x-coordinate of the rectangle upper-left corner
y The y-coordinate of the rectangle upper-left corner
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels




Example

The following code draws a rectangle and paint its outline.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="250"></canvas>
<script>
    var canvas, context, width, height;
    canvas = document.getElementById("myCanvas");
    context = canvas.getContext('2d');
    context.rect(20,20,50,50);<!--   w  w  w  .  j  a  va 2  s .  c o  m-->
    context.stroke();

</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code fills three rectangles.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from   ww  w .j ava 2 s. co m-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    // Red rectangle
    ctx.beginPath();
    ctx.lineWidth = "6";
    ctx.fillStyle = "red";
    ctx.rect(5, 5, 20, 140);  
    ctx.fill();
    
    // Green rectangle
    ctx.beginPath();
    ctx.lineWidth = "4";
    ctx.fillStyle = "green";
    ctx.rect(50, 30, 50, 50);
    ctx.fill();
    
    // Blue rectangle
    ctx.beginPath();
    ctx.lineWidth = "10";
    ctx.fillStyle = "blue";
    ctx.rect(160, 50, 50, 80);
    ctx.fill();
</script> 

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to create square structure.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script type='text/javascript'>
    var canvas= document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
<!--  w  w w  . j a v  a 2  s.c om-->
    var context = canvas.getContext('2d');
    var square = {
        'x': 50,
        'y': 50,
        'width': 100,
        'height': 100,
        'fill': '#000000'
    };
    var render = function() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.rect(square.x, square.y, square.width, square.height);
        context.fillStyle = square.fill;
        context.fill();
    };
    render();
</script>
</body>
</html>

The code above is rendered as follows: