HTML5 has added some new elements, such as canvas,audio,image, relative to HTML.
The canvas element provides a pixel-level canvas for the script, which you can try to render a graphic, game screen, or other virtual image. Canvas elements draw basic shapes such as lines, circles, matrices, and images and basic text. Currently, major browsers have started to support GPU-accelerated 2D canvas rendering, so game animations using canvas-FAI will run fast.
First, add the <canvas> tag to the <body> as follows:
The OnLoad event in the body invokes the function to ensure that the page has been fully loaded before the function is run. This is important when manipulating canvas or image elements, and attempting to access these elements before the browser loads the page completely can cause JavaScript errors.
Next get the canvas drawing environment:
The canvas drawing environment gives us a number of ways to draw content from the game on the screen. These methods mainly include:
- Draws a rectangle.
- Draw complex paths (lines, curves, and so on).
- Draws text.
- Custom Brush styles (color, transparency, texture, and so on).
- Draws an image.
- Pan and rotate.
Draw a rectangle
The canvas uses the origin (0,0) coordinate system in the upper-left corner, the x-axis increments to the right, and the y-axis down. When you draw a rectangle, the following functions are used primarily:
- FillRect (X,y,width,height): Draws a solid rectangle;
- Strokerect (X,y,width,height): Draws a hollow rectangle;
- Clearrect (x,y,width,height): Clears the rectangle of the specified area so that it is completely transparent.
The implementation results are as follows:
Drawing Complex Paths
For drawing of complex graphs such as polygons, circles, etc., the following methods are provided in the canvas:
- Beginpath (): Start drawing a new path;
- Closepath (): Closes the shape by drawing a segment of the current point to the beginning of the path;
- Fill (), stroke (): Fills the shape or draws a hollow shape;
- MoveTo (x, y): Moves the current point to the points (x, y);
- LineTo (x, y): Draws a line segment from the current point to the dot (x, y);
- Arc (x,y,radius,startangle,endangle,anticlockwise): Draws an arc of the specified radius, centered at point (x, y).
The drawing steps are as follows:
- Start drawing using Beginpath ();
- Use MoveTo (), LineTo (), Arc () to create segments;
- Use Closepath () to finish drawing and closing the shape (optional);
- Use Fill (), stroke () to fill the shape or draw the outer border, and use Fill () to automatically close all unclosed paths.
The implementation results are as follows:
Draw Text
Drawing text in the canvas is achieved mainly through the following two functions:
- Stroketext (text,x,y): Draws hollow text at (x, y);
- Filltext (text,x,y): Draws solid text at (x, y);
The implementation results are as follows:
Not to be continued ...
HTML5 Reading notes--canvas elements