
Breakout game
The rectangle method of Canvas has four parameters
The rect and fillRect methods draw squares or rectangular shapes with numerous parameters.
The color and line thickness are set in the same way as for the lines.
The rectangle is drawn within the parameters of position and dimension
The rect function has four parameters:
rect(x, y, w, h)
The parameters are the coordinates of top ans left point, the horizontal length, vertical length.
Example:
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>
The rectangle is filled with the fill function
The fill() method is used to fill a 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.
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:
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 ...
You should also know ...
More