<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 <canvas>
element.
A rectangle can be defined with the following methods:
fillRect()
strokeRect()
clearRect()
rect()
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 #000000
(black).
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:
fillStyle
Example: context.fillStyle = 'red'
strokeStyle
Example: context.strokeStyle = 'blue'
A rectangle can also be defined as part of a path in the following way:
rect()
fill()
and/or stroke()
methods are called.fill()
stroke()