[Data Visualization] Data Visualization Canvas

insert image description here

1. Understand Canvas

◼What is Canvas
---- Canvas was originally introduced by Apple in 2004 for the Mac OS X WebKit component, providing support for applications such as dashboard widgets and the Safari browser. Later, it was implemented by Gecko-kernel browsers (especially Mozilla Firefox), Opera and Chrome, and was proposed by the web hypertext application technology working group as a standard element of the next generation of web technology (HTML5 new element).
---- Canvas provides a lot of JavaScript drawing APIs (such as methods for drawing paths, rectangles, circles, text and images), and elements can draw various 2D graphics.
---- Canvas API mainly focuses on 2D graphics. Of course, you can also use the WebGL API of element objects to draw 2D and 3D graphics.
◼Application scenarios of Canvas
---- It can be used in animation, game screen, data visualization, picture editing and real-time video processing, etc.
◼Canvas Browser Compatibility

insert image description here

2. Advantages and disadvantages of Canvas

◼Canvas Advantages:
---- The functions provided by Canvas are more primitive, suitable for pixel processing, dynamic rendering and drawing with a large amount of data, such as: image editing, heat map, glare trail effects, etc.
---- Canvas is very suitable for image-intensive game development, suitable for frequent redrawing of many objects.
---- Canvas can save the resulting image in .png or .jpg format, which is suitable for pixel-level processing of images.
◼Canvas Disadvantages:
---- On the mobile side, due to the large number of Canvas, the memory usage exceeds the capacity of the mobile phone, causing the browser to crash.
---- Canvas drawing can only be operated by JavaScript script (allinjs).
---- Canvas is a graphic composed of individual pixels, zooming in will make the graphic grainy and pixelated, resulting in blur.

3. First experience with Canvas

◼ Notes on using Canvas:
---- is very similar to element, the only difference is that it does not have src and alt attributes.
---- The label only has two attributes - width and height (the default unit is px). When no width and height are set, the canvas will be initialized with a width of 300px and a height of 150px.
---- Unlike elements, elements must require a closing tag (). If the closing tag is absent, the rest of the document is considered alternate content and will not be displayed.
---- Test the existence of the canvas.getContext() method to check whether the browser supports Canvas.
◼First experience with Canvas
---- Canvas general template
---- Canvas draws a square
insert image description here

4. Canvas Grid and coordinate space

◼Before we start drawing, we need to understand the Canvas grid (canvas grid) and coordinate system.
◼Canvas Grid or coordinate space
----Suppose, there is an element with a width of 150px and a height of 150px in the HTML template. Elements are covered by grid by default.
---- Generally speaking, one unit in the grid is equivalent to one pixel in the canvas element.
---- The origin of the grid is located at the upper left corner of the coordinate (0,0). All elements are positioned relative to this origin.
----The grid can also be understood as a coordinate space (coordinate system). The origin of the coordinates is located in the upper left corner of the canvas element, which is called the initial coordinate system; as shown in the blue square in the right picture, the coordinates of the upper left corner are x from the left Pixels, y pixels from the top, coordinates (x, y)
---- The grid or coordinate space can be transformed, and how to convert the origin to different positions, rotate the grid or even scale it will be described later.
Note: After moving the origin, by default all subsequent transformations will be based on the transformation of the new coordinate system.
insert image description here

5. Draw a rectangle (Rectangle)

◼Canvas supports two ways to draw rectangles: rectangle method and path method.
---- A path is a collection of points of different shapes connected by line segments or curves of different colors and widths.
---- Except for rectangles, other graphics are formed by combining one or more paths.
---- Usually we draw complex graphics through many paths.
◼The rectangle method of Canvas drawing: ---- fillRect(x, y, width, height) :
draw a filled rectangle
---- strokeRect(x, y, width, height): draw the border of a rectangle-
--- clearRect(x, y, width, height): Clear the specified rectangular area and make the cleared part completely transparent.
◼Method parameters:
---- The above methods all contain the same parameters.
---- x and y specify the coordinates of the upper left corner (relative to the origin) of the rectangle drawn on the canvas (undefined is not supported).
---- width and height set the size of the rectangle.
insert image description here

6. Understanding the path

◼ What is a path?
---- The basic element of graphics is path. A path is a collection of points of different shapes connected by line segments or curves of different colors and widths.
---- A path can be composed of many sub-paths, and these sub-paths are all in a list, and all sub-paths (lines, arcs, etc.) in the list will form graphics.
---- A path, even a subpath, is usually closed.
◼ Steps to use path to draw graphics:
---- 1. First, you need to create the path starting point (beginPath).
---- 2. Then use the drawing command to draw the path (arc, lineTo).
---- 3. Then close the path (closePath, not necessary).
---- 4. Once the path is generated, the graphics can be rendered by stroke or fill.
◼ The following are the functions to be used when drawing a path
---- beginPath(): create a new path, after it is generated, the graphics drawing command will be directed to draw on the new path, and will not be associated with the old path.
---- closePath(): After closing the path, the graphic drawing command points to the context before beginPath again.
---- stroke(): Draw the outline/stroke of the graphic through the line (for the current path graphic).
---- fill(): Generate a solid graphic by filling the content area of ​​the path (for the current path graphic).
insert image description here
insert image description here

7. Path - Draw a straight line

◼ Move the brush (moveTo) method
---- The moveTo method cannot draw anything, but it is also a part of the path list
---- moveTo can be imagined as working on paper, the tip of a pen or pencil moves from The process of moving from one point to another.
---- moveTo(x, y): Move the pen to the specified coordinates x and y.
---- When the canvas is initialized or beginPath() is called, we usually use the moveTo(x,y) function to set the starting point.
---- Use the moveTo function to draw some discontinuous paths.
insert image description here
◼ Draw a straight line (lineTo) method
---- lineTo(x, y): Draw a straight line from the current position to the specified (x, y) position.
---- This method has two parameters (x, y) representing the end point of the line in the coordinate system.
---- The start point is related to the previous drawing path, and the end point of the previous path is the next start point.
---- Of course, the starting point can also be changed by the moveTo(x,y) function.
◼ Draw a straight line
---- Step 1: Call beginPath() to generate a path. Essentially, paths are made up of many subpaths (lines, arcs, etc.).
---- Step 2: Call the moveTo and lineTo functions to draw the path (the path can be continuous or discontinuous).
---- Step 3: Close the path closePath(), although not required, usually closes the path.
---- Step 4: Call the stroke() function to stroke the line.
insert image description here

8. Path - draw triangle (Triangle)

◼ Steps to draw a triangle
---- Step 1: Call beginPath() to generate a path.
---- Step 2: Call the moveTo() and lineTo() functions to draw the path.
---- The third step: close the path closePath(), not necessary.
1) The closePath() method will close the graph by drawing a straight line from the current point to the starting point.
2) If the graph is already closed, that is, the current point is the starting point, this function does nothing.
---- Step 4: Call the stroke() function to stroke the line, or call the fill() function to fill it (when fill is used, the path will be automatically closed, but stroke will not).
insert image description here

9. Path - draw arc (Arc), circle (Circle)

◼ To draw an arc or circle, use the arc() method.
---- arc(x, y, radius, startAngle, endAngle, anticlockwise), this method has six parameters:
1) x, y: the coordinates of the center of the circle where the arc is drawn.
2) radius: the radius of the arc.
3) startAngle, endAngle: This parameter defines the start and end arcs in radians. These are all referenced to the x-axis.
4) anticlockwise: It is a Boolean value. If it is true, it is counterclockwise, if it is false, it is clockwise, and the default is false.
◼ Calculation of radians
---- The unit of the angle in the arc() function is radians, not angles.
---- JS expression of angle and radian: radian = ( Math.PI / 180 ) * angle, that is, 1 angle = Math.PI/180 radians
1) For example: rotate 90°: Math.PI / 2; Rotate 180°: Math.PI; Rotate 360°: Math.PI * 2; Rotate -90°: -Math.PI / 2;
◼ Steps to draw an arc
---- The first step: call beginPath() to generate the path.
---- Step 2: Call the arc() function to draw the arc.
---- The third step: close the path closePath(), not necessary.
---- Step 4: Call the stroke() function to stroke, or call the fill() function to fill (when using fill, the path will be automatically closed)
insert image description here

10. Path-Rectangle (Rectangle)

◼ Another way to draw a rectangle:
---- call the rect() function to draw, that is to add a rectangle path to the current path
---- rect(x, y, width, height)
---- draw A rectangle whose upper left corner coordinates are (x, y), width and height are width and height.
◼ Note:
---- When this method is executed, the moveTo(x,y) method automatically sets the coordinate parameter (0,0). That is, the current stroke is automatically reset back to the default coordinates.
insert image description here

11. Path - draw arc (Arc), circle (Circle)

◼ To draw an arc or circle, use the arc() method.
---- arc(x, y, radius, startAngle, endAngle, anticlockwise), this method has six parameters:
1) x, y: the coordinates of the center of the circle where the arc is drawn.
2) radius: the radius of the arc.
3) startAngle, endAngle: This parameter defines the start and end arcs in radians. These are all referenced to the x-axis.
4) anticlockwise: It is a Boolean value. If it is true, it is counterclockwise, if it is false, it is clockwise, and the default is false.
◼ Calculation of radians
---- The unit of the angle in the arc() function is radians, not angles.
---- JS expression of angle and radian: radian = ( Math.PI / 180 ) * angle, that is, 1 angle = Math.PI/180 radians
---- For example: rotate 90°: Math.PI / 2; Rotate 180°: Math.PI; Rotate 360°: Math.PI * 2; Rotate -90°: -Math.PI / 2;
◼ Steps to draw an arc
---- Step 1: call beginPath() to generate the path.
---- Step 2: Call the arc() function to draw the arc.
---- The third step: close the path closePath(), not necessary.
---- Step 4: Call the stroke() function to stroke, or call the fill() function to fill (the path will be automatically closed when fill is used).
insert image description here

12. Path-Rectangle (Rectangle)

◼ Another way to draw a rectangle:
---- call the rect() function to draw, that is to add a rectangle path to the current path
---- rect(x, y, width, height)
---- draw A rectangle whose upper left corner coordinates are (x, y), width and height are width and height.
◼ Note:
---- When this method is executed, the moveTo(x,y) method automatically sets the coordinate parameter (0,0). That is, the current stroke is automatically reset back to the default coordinates.
insert image description here

13. Colors

◼ We have learned many methods of drawing graphics. If we want to color the graph, there are two important attributes to do it:
---- fillStyle = color: Set the fill color of the graph, which needs to be called before the fill() function.
---- strokeStyle = color: Set the color of the graphic outline, which needs to be called before the stroke() function.
insert image description here

◼ color
---- color can be a string representing CSS color value, support: keyword, hexadecimal, rgb, rgba format.
---- By default, both line and fill colors are black (CSS color value #000000).
◼ Note
---- Once the value of strokeStyle or fillStyle is set, the new value will become the default value of the newly drawn graphics.
---- If you want to give the graphics different colors, you need to reset the value of fillStyle or strokeStyle.
◼ Additional Supplement
---- fill() function is for graphic filling, fillStyle attribute is to set the fill color
---- stroke() function is graphic stroke, strokeStyle attribute is to set the stroke color
insert image description here

14. Transparency

◼ In addition to drawing solid color graphics, we can also use canvas to draw translucent graphics.
◼ Method 1: Combine strokeStyle and fillStyle attributes with RGBA:
insert image description here

◼ Method 2: globalAlpha attribute
---- globalAlpha = 0~1
✓ This attribute affects the transparency of all graphics in the canvas
✓ The valid value range is 0.0 (completely transparent) to 1.0 (completely opaque), and the default is 1.0.
insert image description here

15. Line styles

◼The line drawn by calling the lineTo() function can set the style of the line through a series of attributes .
---- lineWidth = value: set line width.
---- lineCap = type: Set the line end style.
---- lineJoin = type: Set the style of the joint between .
---- …
◼ lineWidth
---- The property value of setting line width must be a positive number. The default value is 1.0px, no unit required. (Zero, Negative, Infinity and NaN values ​​will be ignored)
---- Line width refers to the thickness from the center to both sides of the given path. In other words, half the line width is drawn on either side of the path.
---- If you want to draw a line from (3,1) to (3,5) with a width of 1.0, you will get the same result as the second picture.
---- Both sides of the path are extended by half a pixel to fill and render a 1-pixel line (dark blue part)
---- The remaining half pixels on both sides will be filled with the half tone of the actual brush color ( Light blue part)
---- The area where the line is actually drawn is (the light blue and dark blue part), and the fill color is greater than 1 pixel, which is why the line with a width of 1.0 is often inaccurate.
---- To solve this problem, the path must be precisely controlled. For example, a 1px line will extend half a pixel on both sides of the path, then draw a line from (3.5 ,1) to (3.5, 5) like the third picture, and its edge just falls on the pixel boundary, and the filling is accurate A line with a width of 1.0.
insert image description here
◼ lineCap: The value of the attribute determines the appearance of the end point of the line segment. It can be one of the following three:
---- butt truncation, the default is butt.
---- round circle
---- square square◼
lineJoin: The value of the attribute determines the appearance of the connection of line segments in the graph. It can be one of these three:
---- round round
---- bevel bevel
---- miter chute gauge, the default is miter.
insert image description here

16. Draw text

◼ Canvas provides two methods to render text:
---- fillText(text, x, y [, maxWidth])
---- At (x,y) position, fill the specified text
---- Maximum width to draw (optional).
---- strokeText(text, x, y [, maxWidth])
---- At (x,y) position, draw text border
---- Maximum width to draw (optional).
◼ Text style (need to be called before drawing the text)
---- font = value: The style of the currently drawn text. This string uses the same syntax as the CSS font property. The default font is: 10px sans-serif.
---- textAlign = value: text alignment option. Optional values ​​include: start, end, left, right or center. The default value is start
---- textBaseline = value: Baseline alignment option. Possible values ​​include: top, hanging, middle, alphabetic, ideographic, bottom.
---- The default value is alphabetic.
insert image description here

17. Draw pictures

◼ To draw an image, you can use the drawImage method to render it into the canvas. The drawImage method has three forms:
---- drawImage(image, x, y)
---- where image is an image or canvas object, and x and y are its starting coordinates in the target canvas.
---- drawImage(image, x, y, width, height)
---- This method has two more parameters: width and height, these two parameters are used to control the scaling when drawing to the canvas Size
---- drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
---- The first parameter is the same as the others, it is an image or another canvas references. The other 8 parameters are best to refer to the illustration on the right, the first 4 are to define the slice position and size of the image source, and the last 4 are to define the target display position and size of the slice.
◼ Image source, the canvas API can use one of the following types as image source:
---- HTMLImageElement: These images are constructed by the Image() function, or any element.
---- HTMLVideoElement: Use an HTML element as your image source, you can grab the current frame from the video as an image.
---- HTMLCanvasElement: You can use another element as your image source.
----…

18. Canvas painting state - save and restore

◼ Canvas drawing state
---- is a snapshot of the current drawing style and deformation.
---- When the Canvas is drawing, it will generate a corresponding drawing state. In fact, we can store some drawing states in the stack for future reuse.
---- The save and restore methods of the Canvas drawing state are used to save and restore. These two methods have no parameters, and they exist in pairs.
◼ Save and restore (Canvas) painting state
---- save(): save all painting states of the canvas (canvas)
---- restore(): restore all painting states of the canvas (canvas)
◼ Canvas painting state includes :
---- The currently applied deformation (i.e. move, rotate and scale)
---- and these attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit,
shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, font , textAlign, textBaseline…
---- Current clipping path (clipping path)
insert image description here

19. Transform

◼ Like CSS3, Canvas also supports deformation. Deformation is a more powerful method that can move the origin of coordinates to another point, and deformation can rotate and scale the grid.
◼ There are 4 ways to transform the Canvas:
---- translate(x, y): used to move the canvas and its origin to a different position.
---- x is the left and right offset, y is the up and down offset (no unit required), as shown in the right figure.
---- rotate(angle): Used to rotate the canvas around the origin, that is, rotate along the z axis.
---- angle is the radian of rotation, it is clockwise, and the unit is radian.
---- scale(x, y): It is used to increase or decrease the number of pixels of the graphics in the canvas, and to reduce or enlarge the graphics.
---- x is the horizontal scaling factor, and y is the vertical scaling factor. If it is smaller than 1, the graph will be reduced, and if it is larger than 1, the graph will be enlarged. The default value is 1, negative numbers are also supported.
---- transform(a, b, c, d, e, f): Allows direct modification of the transformation matrix. This method is to multiply the current deformation matrix by a matrix based on its own parameters.
◼ Notes:
---- It is a good habit to call the save method to save the state before transforming.
---- In most cases, calling the restore method is much simpler than manually restoring the original state.
---- If you do displacement in a loop without saving and restoring the canvas state, you may end up finding that something is missing, because it is likely to be out of the canvas.
---- Transformation needs to be called before drawing graphics.
insert image description here

20. Move-translate

◼ The translate method, which is used to move the canvas and its origin to a different position.
---- translate(x, y)
---- x is the left and right offset, y is the up and down offset (no unit needed).
◼ Benefits of moving the origin of the canvas
---- If the translate method is not used, all rectangles will be drawn at the same (0,0) coordinate origin by default.
---- The translate method allows us to place graphics arbitrarily without manually adjusting the coordinate values ​​one by one.
◼ Example of moving a rectangle
---- Step 1: Save the current state of the canvas first
---- Step 2: Translate and move the canvas before drawing graphics
---- Step 3: Start drawing graphics, and fill color
insert image description here

21. Rotate-rotate

◼ The rotate method, which is used to rotate the canvas around the origin, that is, along the z axis.
---- rotate(angle)
---- only accepts one parameter: the angle of rotation (angle), which is the value in radians in the clockwise direction.
---- JS expression of angle and radian: radian = ( Math.PI / 180 ) * angle, that is, 1 angle = Math.PI/180 radians.
---- For example: rotate 90°: Math.PI / 2; rotate 180°: Math.PI; rotate 360°: Math.PI * 2; rotate -90°: -Math.PI / 2;
--- - The center point of the rotation is always the original coordinate point of the canvas. If we want to change it, we need to use the translate method.
insert image description here

◼ Rotation case
---- Step 1: Save the current state of the Canvas first, and determine the origin of rotation
---- Step 2: Rotate the canvas before drawing graphics (the coordinate system will rotate accordingly)
--- - Step 3: Start drawing graphics and fill them with colors
insert image description here

22. zoom-scale

◼ The scale method can zoom the canvas. It can be used to increase or decrease the number of pixels of the graphics in the canvas, and to reduce or enlarge the graphics.
---- scale(x, y)
---- x is the horizontal scaling factor, y is the vertical scaling factor, negative numbers are also supported.
---- If it is smaller than 1, the graph will be reduced, and if it is larger than 1, the graph will be enlarged. The default value is 1.
◼ Notes
---- In the initial case of the canvas, the coordinates of the upper left corner are taken as the origin. If the parameter is a negative real number, it is equivalent to mirror inversion with the x or y axis as the axis of symmetry.
---- For example, use translate(0, canvas.height); scale(1,-1); to reverse the mirror image with the y-axis as the axis of symmetry.
---- By default, 1 unit of canvas is 1 pixel. If we set the scale factor to 0.5, 1 unit becomes 0.5 pixels, so the drawn shape will be half of the original. Similarly, when it is set to 2.0, 1 unit corresponds to 2 pixels, and the result of drawing is that the graph is enlarged by 2 times.
◼ Scaling case practice
---- Step 1: Save the current state of the Canvas first, and determine the zoom origin
---- Step 2: Zoom the canvas before drawing graphics
---- Step 3: Start Draw graphics and fill them with color
insert image description here

23. Canvas animation

◼ Canvas drawing is controlled by JavaScript, and it is quite easy to realize some interactive animations. So how does Canvas do some basic animations?
---- The biggest limitation of canvas is that once the image is drawn, it stays that way.
---- If you need to perform animation, you have to redraw all the graphics on the canvas frame by frame (for example, if you draw 60 frames in 1 second, you can draw a smooth animation).
---- In order to achieve animation, we need some methods that can perform redrawing at regular intervals. However, there are three methods in Canvas:
---- There are three methods of setInterval, setTimeout and requestAnimationFrame to periodically execute the specified function for redrawing.
◼ The basic steps for drawing a frame of animation on Canvas (to draw a smooth animation, 60 frames per second is required):
---- Step 1: Use the clearRect method to clear the canvas, unless the content to be drawn next will be completely filled canvas (such as a background image), otherwise you need to clear all.
---- Step 2: Save the canvas state. If you add canvas state settings (style, deformation, etc.), and want to keep the original state every time you draw a frame, you need to save it first. Then restore the original state later.
---- Step 3: Draw animated shapes (animated shapes), that is, draw a frame in the animation.
---- Step 4: Restore the state of the canvas. If the state of the canvas has been saved, you can restore it first, and then redraw the next frame.

24. Draw the second hand-setInterval

◼ Draw the animation of the second hand, the steps of drawing a frame:
---- Step 1: Use the clearRect(x,y, w,h) method to clear the canvas.
---- Step 2: Save the canvas state.
---- Step 3: Modify canvas state (style, moving coordinates, rotation, etc.).
---- Step 4: Draw the second hand graphic (that is, draw a frame in the animation).
---- Step 5: Restore the canvas state and prepare to redraw the next frame.
◼ Defects of the setTimout timer
---- The setTimeout timer is not very accurate, because the callback function of setTimeout is placed in the macro task to wait for execution.
---- If there are unfinished tasks in the microtask, the callback function of setTimeout may not trigger the callback within the specified time.
---- If you want to execute a certain task more smoothly and accurately, you can use the requestAnimationFrame function.
insert image description here

25. Draw the second hand - requestAnimationFrame

◼ requestAnimationFrame function
---- Tell the browser - you want to perform an animation, and ask the browser to call the callback function of this function to update the animation before the next redraw.
---- This method needs to pass in a callback function as a parameter, which will be executed before the browser redraws next time
---- If you want to continue to update the next frame of animation before the browser redraws next time , then the requestAnimationFrame() must be called again in the callback function itself
---- Usually the callback function is executed about 60 times per second, and it may be reduced.
◼ Draw the animation of the second hand, the steps of drawing a frame:
---- Step 1: Use the clearRect(x,y, w,h) method to clear the canvas.
---- Step 2: Save the canvas state.
---- Step 3: Modify canvas state (style, moving coordinates, rotation, etc.).
---- Step 4: Draw the second hand graphic (that is, draw a frame in the animation).
---- Step 5: Restore the canvas state and prepare to redraw the next frame.
insert image description here

26. The solar system rotates

◼ Solar system rotation animation, the steps to draw a frame:
---- Step 1: Use the clearRect(x,y, w,h) method to clear the canvas and initialize the global style.
---- Step 2: Save the canvas state.
---- Step 3: Draw the background, draw the earth (draw the moon), and draw the shadow effect.
---- Step 5: Restore the canvas state and prepare to redraw the next frame.
insert image description here

27. clock

◼ Find the x, y coordinates on the circle:
---- The x, y axis coordinates on the circle are actually ( AB, BC ) on the right, and AC is the clock radius
---- x= AB = cosa * AC => x = Math.cos(rad) * R
---- y= BC = sina * AC => y = Math.sin(rad) * R
---- JS expression of angle and radian: radian =( Math.PI / 180 ) * angle => radian = 1 angle corresponding to radian * angle.
---- For example: rotate 90°: radian is Math.PI / 2; rotate 180°: be Math.PI; rotate 360°: be Math.PI * 2; rotate -90°: be -Math.PI / 2;
---- The coordinates of the i-th hour:
---- x = Math.cos( Math.PI * 2 / 12 * i ) * R
---- y = Math.sin( Math.PI * 2 / 12 * i ) * R
insert image description here

◼ Steps to draw a clock and draw a frame:
---- Step 1: Use the clearRect(x,y, w,h) method to clear the canvas.
---- Step 2: Save the canvas state.
---- Step 3: Draw a white background, draw numbers, draw hour/minute/second hands, draw circles, and draw hour and minute scales.
---- Step 4: Restore the canvas state and prepare to redraw the next frame.
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131117352