Rectangle

In this chapter you will learn:

  1. What are the methods we can use to draw rectangle
  2. How to fill a rectangle

Rectangle methods

Methods used to draw rectangles:

NameDescriptionReturns
clearRect(x, y, w, h)Clears the specified rectanglevoid
fillRect(x, y, w, h)Draws a filled rectanglevoid
strokeRect(x, y, w, h)Draws an unfilled rectanglevoid

x and y are the offset from the top-left corner of the canvas element. The w and h arguments specify the width and height of the rectangle.

Fill a rectangle

<!DOCTYPE HTML><!--   j av a  2 s.c o  m-->
<html>
<head>
<style>
canvas {
      border: thin solid black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="140"> 
    Your browser doesn't support the <code>canvas</code> element 
    </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillRect(10, 10, 100, 100);
            ctx.strokeRect(30, 30, 200, 200);
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to clear a rectangle region
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style