Sultry Canvas

| preface

Before THE advent of HTML5, most of the most beautiful effects on web pages were done with images. This approach can be achieved, but this image approach is “at the cost of low performance”, which is often not the best practice.

We all know that the release of HTML5 has brought many more useful things, including a special tag called Canvas, which is a technology that uses JS to draw graphic images in HTML documents.

Recommended book “Web Front-end Development: DETAILED Explanation of HTML5 Canvas Development”

1.1 Differences between Canvas and SVG:

  • Canvas is dynamically generated using JavaScript and SVG is statically described using XML.

  • Canvas is based on “bitmap”, which is suitable for pixel processing and dynamic rendering. SVG is “vector-based” and is not suitable for pixel processing and static description, and graphics magnification does not affect quality. In other words, Canvas is a “bitmap”, while SVG is a “vector map”.

  • Canvas needs to be redrawn each time a change is made, while SVG does not.

  • Simply put, the relationship between Canvas and SVG is the same as that between “art and geometry”

1.2 Canvas usage steps:

  • Gets a Canvas object as a container for manipulating the drawing graphics image

  • Get the context. All canvas methods are used based on the context

  • Draw graphics

For example,

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <canvas ID ="demo" width="400" height="500"></canvas> <! -- Do not use CSS to set canvas canvas, Var canvas = document.getelementByid ('demo') // Get canvasDOM object Canvas.style. border = '1px solid ' Var cvsCtx = canvas. GetContext ('2d') Cvsctx.moveto (100, 100); Cvsctx.lineto (200, 100); Cvsctx.stroke (); </script> </body> </ HTML >Copy the code

Rendering in the browser

Note: the getContext(” 2D “) method can only fetch 2D objects in Canvas, not 3D objects. 3d objects need to have some knowledge of WebGL, etc. If you are interested, learn about threeJS to get started in 3d world.

These are the recent steps of using this Canvas. In the next chapter, how to use Canvas to draw a straight line graph.