The rectangle method of Canvas

The rect and fillRect methods draw squares or rectangular shapes with numerous parameters.

Breakout game

The Canvas API offers only a few simple shapes but, but much can be done with, for example with a figure as simple as the rectangle as well as the method to draw a circle and a few lines of JavaScript, you have all the elements necessary to make the breakout game. A link is given below to a very simple source code that shows how.

Since the attributes of color and thickness are defined in the same way as for lines, we mainly explain the functions specific to the rectangle, empty or filled.

The rect method has four parameters

rect(x, y, w, h)

The parameters are the coordinates of top and left point, the horizontal length, vertical length.

Example:

Requires a recent browser: Internet Explorer 9, Chrome, Firefox, Safari.

Code complet

<canvas id="canvas1" width="400" height="120">
Requires a recent browser: Internet Explorer 9, Chrome, Firefox, Safari.
</canvas>
<script type="text/javascript">
function rectangle()
{
var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
context.beginPath();
context.strokeStyle="blue";
context.lineWidth="2";
context.rect(10,10,200,100);
context.stroke();
}
window.onload=rectangle;
</script>

A rectangle is filled with the fill function

The fill() method is used to fill any shape. The color is given by the fillStyle attribute while the color of the plot, in this case the edge of the rectangle is given by the strokeStyle attribute.

Requires a recent browser: Internet Explorer 9, Chrome, Firefox, Safari.

Code

<script type="text/javascript">
function rectangle1()
{
var canvas = document.getElementById("canvas2");
var context = canvas.getContext("2d");
context.beginPath();
context.strokeStyle="blue";
context.lineWidth="2";
context.rect(10,10,200,100);
context.fillStyle="yellow";
context.fill();
context.stroke();
}
rectangle1();
</script>

But the fillRect function is simpler

The fill method of context is a general method, which applies to any closed shape, whether formed of straight lines, curves or geometric figures.

The fillRect method draws specifically a solid rectangle. The difference is that he does not plot edge, unlike the other cases.

Sample of filled rectangle with rectFill:

Requires a recent browser: Internet Explorer 9, Chrome, Firefox, Safari.

Code

function rectangle3()
{
var canvas = document.getElementById("canvas3");
var context = canvas.getContext("2d");
context.fillStyle="yellow";
context.fillRect(10,10,200,100);
}
rectangle3();

The code is simple ...

In another chapter, we will see how to make a rectangle with rounded corners, but we must learn how to draw arcs before.

You must know also...