Introduction of Canvas

Before we start learning Canvas, let’s take a look at Flash

Flash in web pages

Flash is widely used in games, online video, website advertising, interaction design and so on

The problem of Flash

  • Flash files can only be opened with a Flash player (including major browsers and video players), and the version of the player must be no later than that of the built-in Flash program.
  • On August 15, 2012, Flash pulled out of the Android platform, officially saying goodbye to the mobile end.
  • On July 25, 2017, Adobe Systems announced that it plans to phase out the Flash player plug-in by the end of 2020.
  • Flash is fading.

The concept of the Canvas

New to HTML5 is < Canvas >, which is an HTML element in which you can draw an image using a script (usually JavaScript). It can be used for photo collections or simple (and not so simple) animations, or even real-time video processing and rendering.

The advantage of the Canvas

  • No plug-ins need to be installed, Canvas is integrated into the browser.
  • Canvas development has its own set of apis, which are implemented through JavaScript and HTML5’s < Canvas > tag.
  • With the optimization of JavaScript engine in various browsers, especially Chrome V8, the efficiency of Canvas operation has been greatly improved.
  • Canvas can run on increasingly important mobile platforms.

Basic Canvas Usage

The < canvas > element

  • The

    tag is a new double tag for HTML5.
  • Compatibility issue: Internet Explorer 9 or earlier browsers do not support it.
  • Solution: Add a prompt inside the double label.
<canvas width="800" height="600" id="myCanvas" >Sorry, your browser does not support canvas, please upgrade your browser</canvas>
Copy the code

The <canvas> tag property

  • Width: indicates the width of the canvas
  • Height: Height of the canvas
  • Id: The ID attribute of the tag that JS uses to get the element
  • Note: The width and height properties can be set in CSS, but they can be distorted and distorted, so if you want to fix the width and height of the canvas, you can set them in the tag properties.

JavaScript Rendering context

The Canvas element itself has no drawing ability, so all drawing work must be done inside JavaScript

JavaScript drawing steps

  • Get the Canvas element via the ID attribute
  • The image will be rendered in the context of the canvas element’s getContext method, similar to creating a new canvas in Photoshop
  • The Canvas API focuses primarily on 2D graphics, so get the 2D context
  • The later drawing work is done in the CTX context

Canvas common drawing method

Coordinates and grids

  • Grid: Canvas elements are covered by grids by default. Typically, a cell in a grid is equal to 1 pixel in a Canvas element.
  • Coordinates: the starting point of the grid is the upper-left corner (coordinates are (0,0)). All elements are positioned relative to the origin.

Stroke and fill

  • Any shape in a Canvas is made up of these two parts.
  • Stroke: Also called stroke.
The name of the methods role
Stroke (Stroke) ctx.stroke() Drawing a graph contour by line does not automatically close the path
fill ctx.fill() The path is closed automatically by filling the content area of the path to generate a solid graph

Graphic style

The path drawn on the Canvas can be customized with color, stroke width and other style Settings

attribute Attribute values role
ctx.lineWidth digital Set the stroke width to a few pixels
ctx.fillStyle Color value Set the fill color
ctx.strokeStyle Color value Sets stroke color

Draw the path

  • Canvas can use corresponding methods to draw the path of any shape.
  • After a path is drawn, it must be stroked or filled before it can be displayed on screen.
  • Path drawing requires multiple methods.
methods role
ctx.beginPath() Create a new instance of the path
ctx.closePath() A closed path
ctx.moveTo(x, y) Sets the starting position and moves the stroke to the specified coordinates X and Y. Discontinuous paths can also be drawn
ctx.lineTo(x,y) Draws a line from the current position to the specified x and y positions

Draw a rectangle

When you draw the path of a rectangle, you can simplify it

methods role parameter
ctx.fillRect(x, y, width, height) Draws a filled rectangle X: horizontal starting position for drawing; Y: vertical starting position for drawing; Width: the width of the rectangle; Height: The height of the rectangle
ctx.strokeRect(x, y, width, height) Draws the border of a rectangle Same as above
ctx.clearRect(x, y, width, height) Clear the specified rectangle so that the clear portion is fully transparent. Generally used to clear the screen. Same as above

Draw arcs and circles

  • To draw arcs or circles, we use the Arc () method.
  • Arcs belong to paths and must begin with beginPath(). Arcs or circles must be stroked or filled to display.
methods role parameter
ctx.arc(x, y, r, start, end, anticlockwise) Draws an arc or circular path X: horizontal position of the center of the circle Y: vertical position of the center of the circle R: radius of the circle Start: Angle of the beginning of the circle (radians) end: Angle of the end of the circle (radians) anticlockwise: Set the direction of the drawing, Boolean value. The default is false clockwise, true counterclockwise

Pay attention to

  • The units of Angle in the ctx.arc() function are radians, not angles.
  • JS expression for Angle and radian: Radian = (math.pi / 180) * Angle.
  • 1 radian ≈ 57°
  • Special angles such as:
    • 180 degrees = math.pi radians
    • 360° = Math.pi * 2 radians

Draw text

Text drawn on Canvas can also be set to the relevant style of text

Methods and Properties role parameter
ctx.fillText(text, x, y [, maxWidth]) Fills the text at the specified position X: the horizontal starting position to draw. Y: the vertical starting position to draw. MaxWidth: The maximum width to draw
ctx.strokeText(text, x, y [, maxWidth]) Draws a text border at the specified position Same as above
ctx.font Setting font Properties Property value: “Font size”
ctx.textAlign Sets the text alignment property Ownership values: start,end,left,right, center The default value is start

Deformation in Canvas

deformation

  • Canvas deformation is a powerful way to move the origin to another point, rotate and scale the mesh.

mobile

  • Ctx.translate (x, y) moves the position of the origin.
  • X is the left/right offset and y is the up/down offset.

rotating

  • Ctx. rotate(Angle) Rotates the canvas around the origin. The Angle of rotation, “Angle,” which is clockwise and measured in radians.

The zoom

  • Ctx.scale (scaleWidth, scaleHeight) scales the current drawing to a larger or smaller size.
  • Parameters: are numbers that represent a multiple of the width and height of the zoom.
  • If you scale the drawing, all subsequent drawing will be scaled, as will the positioning.

State saving and recovery

  • Canvas can save the current state to the memory. Once the state is changed, such as deformation, it can be restored to the saved state through restoration method in the later stage.
  • Save and restore are mostly used for complex graphics
The name of the methods role
save ctx.save() Saves all the current states of the canvas
restore ctx.restore() Restores the last saved state

Canvas image usage and management

The plot

  • The common method of introducing images to canvas requires the following three basic operations:
    • Create an Image object using the new Image() method
    • Set the SRC property to the image object to get the URL.
    • After the image is loaded, use the ctx.drawImage() function to draw the image onto the canvas

CTX. DrawImage () method

  • The ctx.drawImage() function can draw a complete image or a slice according to the number of parameters.
    • Ctx. drawImage(image, x,y) : drawImage at the specified (x,y) position
    • Ctx. drawImage(image, x, y, width, height) : to scale the image
    • Ctx. drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) : Draw a section in the image at the specified position (dx,dy). The starting position of the section in the original picture is (sx, SY), and the width and height of the section are sWidth and sHeight.

Canvas motion method

Simple movement

  • Probably the biggest limitation of a canvas is that once the image is drawn, it stays that way. If we need to move it, we have to redraw everything, including the previous ones. Redrawing is time-consuming, and performance depends on the speed of your computer.
  • Canvas movement formation process: must constantly redraw a new rectangle! Use visual retention to create movement!
  • Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render → Clear screen → Update → Render…