Draw a Rectangle using the HTML <canvas> Tag
<canvas id="myCanvas" width="350" height="590"> <p>Fallback content for browsers that don't support the canvas tag.</p> </canvas> <script> var canvasRect = document.getElementById("myCanvas"); var ctxRect = canvasRect.getContext("2d"); // Using fillRect() ctxRect.fillRect (5, 5, 180, 100); // Using clearRect() ctxRect.clearRect(20, 20, 50, 70); // Using strokeRect() ctxRect.strokeRect (5, 130, 180, 100); // Using rect() with fill() ctxRect.beginPath(); ctxRect.rect(5, 260, 180, 100); ctxRect.fill(); // Using rect() with stroke() ctxRect.rect(5, 380, 180, 100); ctxRect.stroke(); </script>
The above example demonstrates five different ways to draw a rectangle using the HTML
A rectangle can be defined with the following methods:
- Paints the given rectangle onto the canvas, using the current fill style.
- Paints the box that outlines the given rectangle onto the canvas, using the current stroke style.
- Clears all pixels on the canvas in the given rectangle.
- Defines the rectangle but requires further methods before it's painted it to the canvas. This is a path command and is intended to be used when creating a path. See below for more info.
The above methods allow you to specify the width, height and coordinates of the rectangle. The default color of the rectangle is black — if nothing further is specified when the context is created, the rectangle will have a stroke and fill value of
Style a Rectangle
You can change the rectangle's color from the default black. A rectangle can have its stroke and/or fill styles defined in the following ways:
- Allows you to fill the rectangle with the color specified.
context.fillStyle = 'red'
- Represents the color or style to use for the rectangle's stroke (i.e. the rectangle's outline).
context.strokeStyle = 'blue'
Create a Rectangle within a Path
A rectangle can also be defined as part of a path in the following way:
- This method adds a new closed subpath to the path (in the form of a rectangle). The rectangle isn't actually painted to the canvas until either the
stroke()methods are called.
- Fills the subpaths of the current path or the given path with the current fill style.
- Strokes the subpaths of the current path or the given path with the current stroke style.