Basic principles of canvas

Time:2021-9-15

After a year, it was abandoned for more than a month. Recently, I just came into contact with canvas. To sum up some concepts, canvas is a pixel based image API. The biggest difference between canvas and SVG is that canvas needs to be redrawn (canvas needs to be redrawn when removing pictures, while SVG can edit pictures by editing element nodes), and based on pixel based rendering (SVG is a vector as the name suggests), a more detailed comparison mark is here:?What are the advantages of SVG and HTML5 canvasAnd I personally think that although the canvas API is also very complex, SVG is more complex and embarrassing RZ. Here are the concepts I think need to be clarified during my contact with canvas.

Infrastructure

The canvas element itself does not have any appearance. It is a blank drawing board and a set of APIs provided to JS. It was first introduced by safari. Before IE9, some class libraries can be used to simulate canvas in ie. most APIs are not defined in the canvas element itself. The attributes of the canvas element are not much different from those of conventional HTML elements. Its drawing APIs are defined in oneCanvasRenderingContext2DObject (simply translated into context object here), which passes throughgetContext()Method, code example:

<html>
<head>
< title > coordinate system demo < / Title >
</head>
<body>
<canvas id = 'square' width= 200 heigth=200></canvas>
</body>
<script>
var canvas = document.getElementById('square')
Var CTX = canvas. Getcontext ('2d ') // 2D represents the dimension of the sketchpad. Entering 3D will get a more complex 3D graphics API, also known as webgl

The default coordinate system is the same as the current coordinate system

Image drawing requires reference coordinate system positioning. The default coordinate system of canvas is the origin of the upper left corner of the canvas (0,0). However, if an image is drawn with reference to a fixed point every time, it will lack flexibility. Therefore, canvas introduces the concept of “current coordinate system”. The so-called “current coordinate system” refers to the coordinate system referenced by the image when it is drawn at this time, which will also be used as the image state (the concept of image state will be introduced later). For examplerotateRotation operation, change the current coordinate system, that is, changerotateIf you don’t have the concept of the current coordinate system, don’t you have to refer to the origin in the upper left corner of the canvas for operations such as rotation, scaling and tilt (the default coordinate system)?

Canvas providestranslate()andsetTransform()These two methods affect the current coordinate system and the default coordinate system respectively.

translate()AndsetTransform()method

translate()Method to move the coordinate origin up, down, left and right. What it affects is the “current coordinate system” that the image refers to when drawing, for example:

You can operate and observe directly in the demo:

Coordinate system demo

code:

<html>
<head>
< title > coordinate system demo < / Title >
</head>
<body>
<canvas id = 'square' width= 200 heigth=200></canvas>
</body>
<script>
var canvas = document.getElementById('square')
var ctx = canvas.getContext('2d')

ctx.beginPath()
Ctx.translate (20,20) // translate affects the current coordinate system
ctx.moveTo(0,0)
ctx.lineTo(100,20)
ctx.stroke()
</script>
</html>

Image drawing without any coordinate system change:

Basic principles of canvas

translate()Method to move the original coordinates to (20,20) to obtain the drawing of the current coordinate system

Basic principles of canvas

After knowing thissetTransform()It is also easy. This method affects the default coordinate system, that is, it does not move the origin around, but resets the current coordinate system and defines a new default coordinate system. What does it mean to affect the default coordinate system, such as the previous onetranslate()The moved coordinate origin (0,0) is still the initial default coordinate system, and nowsetTransform()What is affected is the coordinate system of the origin (0,0), or the previous demo, when addedctx.setTransform(1,0.5,-0.5,1,30,10)After this statement, the image drawing will become:

Basic principles of canvas

that is becausesetTransform()The default coordinate system is redefined, sotranslate()Get the current coordinate system based on the new default coordinate system. Understanding these two concepts will master the transformation of coordinate system in canvas.

setTransform()Andtransform()method

setTransform()This API is slightly more complex, and the parameters it accepts are the same astransform()(use)transform()A transformation structure can be obtained directly, which can replacerotate()And other methods, and more flexible) with 6 parameters,setTransform(a,b,c,d,e,f)The principle of coordinate system change is obtained through the following operations with these six parameters:

x’ = ax + cy +e
y’ = bx + dy +f

This coordinate system transformation is also called affine transformation. For the chestnuts of this transformation, please refer to these two Blogs:
?Relationship between HTML5 canvas transformation matrix and coordinate deformation

route

Path is the basis for drawing all graphics, which is different from that in SVGpathUse propertiesM,L,AAnd other control XML documents, canvas calls the method of the context object to complete the drawing of the path, and callsbeginPath()Start a new path, and each path has sub paths. It is these sub paths that make the graph take shape. callbeginPath()Post callMoveTo()Start a sub path. Use after drawingclosePath()Close the path to form a closed area, which can be used at this timefill()Wait for the method to fill the area. Each time you start drawing a new path, you must call it againbeginPath()Otherwise, the newly drawn path continues to be drawn as a child of the previous path.

be similar tolineTo()It is the simplest straight line path method, and canvas also providesbezierCurveTo()andquadraticCurveTo()These complex curve path methods are very complex, so it is estimated that this operation should be solved first.

In addition, it should be noted that when the two sub paths of a path do not intersect (such as drawing a hollowed out figure), the canvas will use the “non-zero winding principle” to judge whether a point is inside or outside the path, so as to distinguish which areas need to be filled when filling.

For the principle of non-zero winding number principle, please refer to here: mark?Nonzero surround number rule and odd even rule

Image status of canvas

The properties and methods of canvas are not very different from those of our object-oriented methods, but the concept of image state is involved here. In canvas, cannot passgetContext()Method to obtain multiple context objects, and the image attributes are canvas based context objects, that is, you can’t have two attributes at the same time. Figuratively, image attributes are like brush, thickness, size and color. Since there can only be one context object at a time, only one brush can be used at a time. At this time, when other image attributes (another brush) are required, you can only switch by saving the current image state and then creating a new image state.

You need help at this timesave()andrestore()To switch the image state, each timesave()The current image state will be saved. The image state includes the current image attribute, current coordinate system, clipping region and other information. For example, the following demo draws lines in two colors:

Modify the code directly in the demoImage status demo
JS code:

var canvas = document.getElementById('square')

var ctx = canvas.getContext('2d')

ctx.beginPath()
ctx.strokeStyle = "red"
ctx.moveTo(0,0)
ctx.lineTo(100,20)
ctx.stroke()
CTX. Save() // save the current image status (brush)

ctx.beginPath()
ctx.strokeStyle = "blue"
ctx.moveTo(0,0)
ctx.lineTo(100,40)
ctx.stroke()
CTX. Restore() // restore to the recently saved image state (brush)

ctx.beginPath()
ctx.moveTo(0,0)
ctx.lineTo(100,60)
ctx.stroke()

The output is as follows:

Basic principles of canvas

These image attributes include:

  • fillStyle

  • font

  • globalAlpha

  • globalCompositeOperation

  • lineCap

  • lineJoin

  • lineWidth

  • miterLimit

  • textAlign

  • textBaseline

  • shadowBlur

  • shadowColor

  • shadowOffsetX

  • shadowOffsetY

  • strokeStyle

Canvas background

General solid background filling can be usedfillStyleProperty, but when it comes to more complex images or gradient filling, it is requiredCanvasPatternandCanvasGradientObject, you cancreatPattern()Method obtainedCanvasPatternIt should be noted here that the API can not only substitute general pictures, but also use canvas elements, such as an invisible canvas element outside the picture for insertion.
For details of these two APIs, refer directly to the documentation:

?CanvasPattern
?CanvasGradient

Pixel operation

Pixel based canvas can realize the operation for a single pixel, which is also the API at the bottom of the canvasgetImageData()Method returns aImageDataObject that represents the original RGBA pixel information in the canvascreatImageData()Method can also create an emptyImageDataObject, lastputImageData()Method to output the processed pixels to the canvas.

Microsoft has a good tutorial(Use canvas to turn color photos into black and white photos)Explain the pixel operation, in which the operation is to turn the color photo into gray. The principle is to extract the three RGB components and re assign them to the gray variable after calculation (the key calculation statements are as follows).

myGray = parseInt((myRed + myGreen + myBlue) / 3);

          // Assign average to red, green, and blue.
          myImage.data[i] = myGray;
          myImage.data[i + 1] = myGray;
          myImage.data[i + 2] = myGray;

Recommended Today

Making Ubuntu installation USB flash disk for Mac OS

Installing Ubuntu system with USB flash disk is one of the common installation methods at present. There are tools for making and installing USB flash disk on windows (such asUniversal USB Installer), so inMac OSHow to make and install USB flash disk?The answer iscommand line! hdiutil The first step is toUbuntuDownload the required Ubuntu installation […]