I have not been exposed to Canvas much before. I have used the game engine to develop transition scene games and used Canvas to compress pictures. However, I forgot all the time after using it, because I have not consulted relevant API usage systematically, and the knowledge has not formed a system. Today, I plan to learn about Canvas in earnest.

This is the 12th day of my participation in the August Text Challenge.More challenges in August

Canvas Basic Introduction

The Canvas API provides a way to draw graphics using JavaScript and HTML’s < Canvas > element. It can be used for animation, game graphics, data visualization, image editing, and real-time video processing.

  • Not to mention animations, just update the canvas every once in a while.
  • Data visualization is a common scenariod3,echartsAll usecanvasDraw some charts
  • Can be used for image editing (compression, cropping, etc.), video processing (get the current frame image of the video to draw to the canvas)

So you can see that Canvas is still very important. Above all scene almost without an interface: CanvasRenderingContext2D, 2 d drawing context, we called canvas below unified CTX for short. Today we are going to focus on its grammar and usage.

CanvasRenderingContext2D common API

Draw a rectangle

There are three types of rectangles in canvas:

  • Translucent rectangle
  • Fill the rectangle
  • Stroke rectangle

Three different APIS are used:

ctx.clearRect

Erases a rectangular area by setting the pixel to transparent

void ctx.clearRect(x, y, width, height);
Copy the code

ctx.fillRect

Used to draw a fill rectangle, setting the fillStyle of the rectangle pair via the fillStyle property

void ctx.fillRect(x, y, width, height);
Copy the code

ctx.strokeRect

This method draws a stroke rectangle (default stroke is 1)

void ctx.strokeRect(x, y, width, height);
Copy the code

Draw text

There are several factors to consider when drawing text:

  • Set the width of the text
  • Stroke the text
  • Fetch before drawing

Occupy has three important benchmarks, text

ctx.fillText

// Note that the text starts at x and draws the left side with y as the baseline for the text. Void ctx.fillText(text, x, y, [maxWidth]) void ctx.fillText(text, x, y, [maxWidth]);Copy the code

ctx.strokeText

Draw stroke text. It’s fun

void ctx.strokeText(text, x, y [, maxWidth]);
Copy the code

ctx.measureText

Returns information about the TextMetrics object contained in the measured text (such as its width)

ctx.measureText(text);
Copy the code

To be continued

Thanks for reading, and this series will continue to be updated