Basic usage of canvas and drawing shapes

<canvas> is an HTML element that can use script (usually javascript) to draw graphics. It can make picture composition, draw charts or simple animations, as shown below:

Except for some outdated browsers that do not support the <canvas> element, all new versions of mainstream browsers support it. The default size of the Canvas is 300 pixels wide by 150 pixels high.

01 Basic usage

<canvas> element

<canvas id="myCanvas" width="150" height="150"></canvas>

<canvas> looks like the <img> element, the only difference is that it does not have the src and alt attributes. In fact, the <canvas> tag has only two attributes: width and height.

The rendering context

The <canvas> element creates a fixed-size canvas that exposes one or more rendering contexts that can be used to draw and manipulate the content to be displayed.

The canvas is initially blank. To demonstrate, first the script needs to find the rendering context and then draw on it.

var canvas = document.getElemenById('myCanvas);var ctx = canvas.getContext('2d')

The first line of code gets the DOM object for the <canvas> element whose id is myCanvas.

Once we have the element object, we can access the drawing context by using its getContext() method.

A simple example:

<canvas id="myCanvas" width="300" height="150"></canvas><script type="text/javascript">  function draw(){
   
       let canvas = document.getElementById('myCanvas');    if(canvas.getContext){ // 检查浏览器是否支持canvas标签      let ctx = canvas.getContext('2d');                ctx.fillStyle = "red";      ctx.fillRect(10, 10, 50, 50);                ctx.fillStyle = "rgba(0, 0, 200, .5)";      ctx.fillRect(30, 30, 50, 50);    } else {
   
         //canvas-unsupported code here    }  }  draw();</script>

After executing the draw function, we will get an image like the following:

02 Draw the shape

Next, we can dig into how to draw rectangles, triangles, arcs and curves on the canvas.

Before drawing objects to the canvas, you need to master the path. Let's see how to do it.

canvas grid

Before we start drawing, we need to understand the canvas grid and coordinate space.

As shown in the figure below, the canvas element is covered by the grid by default. Generally speaking, one cell in the grid is equivalent to one pixel in the canvas element.

The starting point of the grid is the upper left corner with coordinates (0,0). All elements are positioned relative to the origin.


Therefore, the coordinates of the upper left corner of the blue square in the figure are x pixels from the left and y pixels from the top, and the left mark is (x, y).

draw rectangle

<canvas> only supports two forms of graphics drawing: rectangle and path (a line segment connected by a series of points).

All other types of graphics are composed of one or more paths. There are many methods of path generation that make the drawing of complex shapes possible.

First, we go back to drawing the rectangle. Canvas provides three methods to draw rectangles:

   1. Draw a filled rectangle

fillRect(x, y, width, height)

    2. Draw a rectangle border

strokeRect(x, y, width, height)

    3, Clear the specified rectangular area and make the cleared part completely transparent

clearRect(x, y, width, height)

Each of the methods provided above contains 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. width and height set the dimensions of the rectangle.

Still a simple example

function draw(){
   
     let canvas = docment.getElementById('myCanvas');  if(canvas.getContext){
   
       let ctx = canvas.getContext('2d');        ctx.fillRect(20, 20, 100, 100);    ctx.clearRect(40, 40, 60, 60);    ctx.strokeRect(50, 50, 50, 50);  }}

After executing the function, the following graph is obtained:

The fillRect() function draws a black square with coordinates (20, 20) and a side length of 100px.

The clearRect() function erases a 60x60px square starting at coordinates (40, 40),

The strokeRect() function starts at coordinates (50,50) and draws a 50x50px square border.

Different from the path function to be introduced next, the above three functions will appear on the canvas immediately after drawing, and take effect immediately.

draw path

The basic element of a graph is a path.

A path is a collection of points of different shapes connected by line segments or curves of different colors and widths.

A path, or even a subpath, is closed. Drawing shapes with paths requires a few extra steps.

  1. First, you need to create the path starting point;

  2. Then use the drawing command to draw the path;

  3. Then close the path;

  4. Once the path is generated, you can render the shape by stroking or filling the path area.

Here are some functions used:​​​​​​​​

beginPath() 新建一条路径,生成之后,图形绘制命令被指向到路径上生成路径
closePath() 闭合路径之后图形绘制命令又重新指向到上下文中
moveTo(x, y)移动笔触,将笔触移动到指定的坐标x以及y上
lineTo(x, y)绘制直线,绘制一条从当前位置到指定x以及y位置的直线
arc(x, y, radius, startAngle, endAngle, anticlockwise)绘制圆弧或者圆。画一个以(x, y)为圆心,以radius为半径的圆弧(圆),从startAngle开始到endAngle结束,按照anticlockwise给定的方向(默认为顺时针)来生成。
stroke()通过线条来绘制图形轮廓。
fill()通过填充路径的内容区域生成实心的图形。

The first step in generating a path is called beginPath(). Essentially, a path is made up of many subpaths, all in a list, and all the subpaths (lines, arcs, etc.) make up the graph. And every time this method is called, the list is cleared and reset, and then we can redraw new graphics.

The second step is to call functions to specify the drawing path, such as moveTo(), lineTo(), arc().

The third step is to close the path closePath(), but it is not necessary.

When you call the fill() function, all unclosed statuses are automatically closed, so you don't need to call closePath(). But it will not be closed automatically when stroke() is called.

Let's draw two triangles

function draw(){
   
     let canvas = docment.getElementById('myCanvas');  if(canvas.getContext){
   
       let ctx = canvas.getContext('2d');        //填充三角形    ctx.beginPath();    ctx.moveTo(75, 50);    ctx.lineTo(100, 75);    ctx.lineTo(100, 25)    ctx.fill()        //描边三角形    ctx.beginPath();    ctx.moveTo(175, 50);    ctx.lineTo(200,75);    ctx.lineTo(200,25);    ctx.closePath()    ctx.stroke()  }}

After running the function, the following graph is obtained:

Alright, let's stop here for today~~

Guess you like

Origin blog.csdn.net/weixin_49707375/article/details/128220631