Note: In this section, you must have the JS Foundation to better understand the content. Today, we will teach you how to draw rectangles on the canvas. When you learn this, you can do some exercises and reply to the exercises. Everyone will be enthusiastic to help you with your guidance, when we make progress together. Draw moment ...,.
Note: In this section, you must have the JS Foundation to better understand the content.
Today, we will teach you how to draw rectangles on the canvas. When you learn this, you can do some exercises and reply to the exercises. Everyone will be enthusiastic to help you with your guidance, when we make progress together.
To draw a rectangle:
1. Create a canvas label on the page
First, create a canvas label on the page, because all our operations must be completed on the canvas element.
2. Use js to get the canvas Element
Because you need to call the object method provided by canvas to draw images, the second part is to use document. getElementById and other methods to obtain the canvas object.
3. Get Context
Graphics context is used for drawing. It is an object that encapsulates many drawing functions. You need to use the getContext method of the canvas object to obtain the graphic context graphics context. In the draw function, set the parameter to "2D ".
Note: You may think, "can you set it to 3D or 4D ?", The answer is, absolutely not.
4. Fill in the drawn border
When you use the canvas Element to draw a graph, you can use either of the following methods: fill and stroke ). Filling refers to filling the interior of the image; drawing the border refers to drawing only the outer frame of the image without filling the interior of the image. The Canvas element can be used together to draw a graph.
If you do not understand it yet, we will use CSS to understand it.
If we regard the drawn image as p, the CSS border is stroke, and the CSS background is fill. When the two do not exist, there is nothing in the canvas, it is like a blank and transparent p.
5. Set the drawing style
When drawing a drawing, you must first set the style of the drawing, and then call the relevant method to draw the drawing.
6. Specify the line width
Use the lineWidth attribute provided by the canvas object to set the Border width of the graphic. When drawing a graphic, any line can be specified by the lineWidth attribute.
7. Specify the color value
We use the fillStyle attribute and strokeStyle attribute to specify the color, which is the same as setting the color in CSS, you can use hexadecimal color values such as red, blue, or # ff0000, or rgb (red, green, and blue) and rgba (Red value, green value, blue value, transparency) to specify the color.
8. Draw a rectangle
Use the fillRect method and strokeRect method to fill the rectangle and draw the border of the rectangle.
We only need to use the above steps to draw a simple image.
Case
-
-
- HTML5 Canvas labels for daily training-draw a rectangle
-