Draw a rectangle in HTML5 Canvas, html5canvas
This article describes how to draw a rectangle in HTML5 Canvas. This article uses three APIs: fillRect, strokeRect, and clearRect. For more information, see
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 ry built in Canvas-rectangle painting. There are three ways to draw a rectangle in a Canvas: fillRect, StrokeRect, and clearRect ). Of course, we can also use "paths" to depict all images including rectangles.
The following are APIs of the above three methods:
1. fillRect (x, y, width, height ). Draw a solid rectangle starting from (x, y) with width and height.
2. strokeRect (x, y, width, height ). Draw a rectangle frame starting from (x, y) with width and height. The rectangle is rendered into different styles Based on the strokeStyle, lineWidth, lineJoin, and miterLimit attributes currently set.
3. clearRect (x, y, width, height ). Clear the rectangular area with width and height starting from (x, y) to make it completely transparent.
Before calling the above method to draw a Canvas, we need to set the style of filling and stroke. The most basic way to set these styles is to use a 24-bit color (represented by a hexadecimal string ). The following is a simple example:
The Code is as follows:
Context. fillStyle = "#000000 ";
Context. strokeStyle = "# ff00ff ";
In the following example, the fill color is set to black, and the stroke color is set to purple:
The Code is as follows:
Function drawScreen (){
Context. fillStyle = "#000000 ";
Context. strokeStyle = "# ff00ff ";
Context. lineWidth = 2;
Context. fillRect (10, 10, 40, 40 );
Context. strokeRect (0, 0, 60, 60 );
Context. clearRect (20, 20, 20, 20 );
}
Shows the code execution result: