HTML <canvas> Tag with the strokeRect() Method
<canvas id="myCanvas" width="350" height="350">
<p>Fallback content for browsers that don't support the canvas tag.</p>
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Default stroke
ctx.strokeRect (5, 5, 170, 120);
// Orange stroke
ctx.strokeStyle = "Orange";
ctx.strokeRect (5, 170, 170, 120);
</script>
The above rectangles are drawn using the HTML <canvas>
element in conjunction with the strokeRect()
method.
The strokeRect()
method accepts four parameters: strokeRect(x,y,w,h)
.
x
- Horizontal coordinates that the rectangle should start at. This is the number of pixels in from the left.
y
- Vertical coordinates that the rectangle should start at. This is the number of pixels in from the top.
w
- Width of the rectangle.
h
- Height of the rectangle.
Styles
The strokeRect()
method paints the given rectangle onto the canvas, using the current stroke style. The default color is #000000
(black), so your rectangle will be black if a stroke style hasn't yet been specified.
In the above example, the first rectangle has a black stroke because this is the default color (and we didn't specify a strokeStyle
). The second rectangle has an orange stroke because we specified the color with strokeStyle
.
You can also use fillStyle
along with the fillRect()
method to fill a rectangle with a solid color or gradient.