Canavas rectangular method

The rectangle plot on the HTML 5 graphic surface using rect or fillRect has many parameters.

Playing brick wall

The Canvas API offers only a few simple forms, but a lot can be done, for example, with such a simple figure as a rectangle, as well as with the method of drawing a circle, and a few lines of JavaScript, there are all the necessary elements to create a brick wall game. Below you will find a link to very simple source code that shows how.

Because the stroke color and stroke thickness attributes are set in the same way as for lines, we will explain the rectangle-specific functions, either blank or solid .

rect method with four parameters

rect(x, y, w, h)

The arguments are the coordinates of the upper left point, horizontal length, vertical length.

Example:

Requires a fresh browser.

Full code

<canvas id="canvas1" width="400" height="120">
Requiert un navigateur récent: 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>

Rectangle filled with fill

The fill () method allows you to fill any shape. The color is specified by the fillStyle attribute, and the color of the outline, in this case the borders of the rectangle are specified by the strokeStyle attribute.

Requires a fresh browser.

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 in-place population method is a general method that applies to any closed shape, whether straight lines, curves, or geometric shapes.

The fillRect method specifically draws a full rectangle. The difference is that it has no boundary contour, unlike the other case.

An example of a complete rectangle with rectFill:

Requires a fresh browser.

Code

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

Code simplified ...

In the next chapter, we will see how to draw a rectangle at rounded corners, but first we need to learn how to draw arcs.

You may also know...