This article mainly introduces the examples of drawing rectangles in HTML5 Canvas. This article uses three APIs: fillRect, strokeRect, and clearRect. Friends who need it can refer to it.
This article is translated from Steve Fulton & Jeff Fulton HTML5 Canvas, Chapter 2, The Basic Rectangle Shape.
Let's take a look at the simple geometric shape built in Canvas - drawing rectangles. In Canvas, there are three ways to draw a rectangle: fillRect, stroke (StrokeRect), and clearRect. Of course, we can also use paths to depict all the figures including rectangles.
Here are the APIs for the above three methods:
1.fillRect(x,y,width,height). Draw a solid rectangle starting from (x,y), width and height.
2.strokeRect(x,y,width,height). Draw a rectangular box starting from (x,y), width and height. The rectangular box will be rendered into different styles according to the current set strokeStyle, lineWidth, lineJoin and miterLimit properties.
3.clearRect(x,y,width,height). Clear the rectangular area starting from (x,y), width and height, making it completely transparent.
Before calling the above method to draw Canvas, we need to set the style of fill and stroke. The most basic way to set these styles is to use 24-bit colors (denoted in hexadecimal strings). Here is a simple example:
Copy the code