Getting Started with canvas/Basic Grammar

getting started with canvas

1. What is a canvas

CanvasThe Chinese name is "canvas", which is HTML5a new label.

CanvasAllows developers to JSdraw various patterns on this label.

CanvasThere are many ways to draw paths, rectangles, circles, characters and pictures.

CanvasCan "replace" pictures in some cases.

CanvasIt can be used in animation, games, data visualization, picture editor, real-time video processing and other fields.

2. Steps to draw graphics using canvas

​ a. Create a canvas element in html

​ b. Get the canvas tag through js

c. Get the drawing tool from the canvas tag

​ d. Use the drawing tool to draw the graph line on the canvas label

<canvas id="cvs"></canvas> // 步骤a

<script>
    let cvs = document.getElementById('cvs') // 步骤b
    let ctx = cvs.getContext('2d'); // 步骤c
    <!-- 步骤d -->
    ctx.moveTo(100, 100); // 起点坐标
    ctx.lineTo(200, 100); // 下一个点的坐标
    ctx.stroke(); // 将所有坐标用一条线连起来
</script>

**Note: **canvas has a default width and height of 300px*150px, you cannot use css to set the width and height of the canvas, otherwise the content will be stretched (canvas provides two properties of width and height to set the width and height)

3. Coordinate system

It is opposite to the y-axis of the coordinate system in mathematics (the positive direction of the y-axis is downward, and the origin is in the upper left corner of the browser)

4. Line

The default width of the line is 1px, and the default color is black (but by default, the canvas will align the center point of the line with the bottom of the pixel, so the display effect will be 2px and non-pure black problem)

  • lineWidth : the thickness of the line

  • strokeStyle : the color of the line

  • lineCap : line cap, the shape of the two ends of the line. If this value is set, the line will be slightly longer (default: butt; circle: round; square: square)

  • lineJoin : corner style (default: miter; round: round; bevel: bevel)

  • setLineDash(): To change the line into a dashed line, you need to pass in an array of numeric types (the array has only one element: the solid line and blank are both the values; the array has two elements: the solid line is element one, and the dashed line is element two)

  • lineDashOffset(): Set the starting offset of the dotted line

  • beginPath() : new path;

    ​ When drawing multiple line segments with different styles, it is necessary to open up a new path, otherwise the line styles will pollute each other;

    ​ Use the beginPath() method to re-open a path and set the style of the new line segment (required);

let cvs = document.getElementById('cvs')
let ctx = cvs.getContext('2d');
ctx.moveTo(100, 50);
ctx.lineTo(290, 50);
ctx.stroke();

ctx.moveTo(100, 80.5);
ctx.lineTo(290, 80.5);
ctx.stroke();

// 虚线
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(290, 100);
ctx.setLineDash([10])
ctx.stroke();

insert image description here

5. Rectangle

You can use the previous line segment to draw a rectangle, and canvas also provides the rect() method to directly generate a rectangle.

// 线段方式
let cvs = document.getElementById('cvs')
let ctx = cvs.getContext('2d');
ctx.moveTo(100, 100);
ctx.lineTo(200, 100);
ctx.lineTo(200, 200);
ctx.lineTo(100, 200);
ctx.lineTo(100, 100); // 需要再设置一次起点坐标进行闭合 或者推荐使用closePath()方法
ctx.stroke();

rect() method: Parameters 1 and 2 correspond to the starting point (upper left corner) coordinates X and Y respectively, and parameters 3 and 4 represent the width and height of the rectangle

// rect(x, y, width, height)
ctx.rect(150, 50, 50, 99);
ctx.stroke();

strokeRect() ; Stroke rectangle; (usage and parameters are the same as rect())

fillRect() ; fill rectangle;

clearRect() ; Clear the specified area (use ctx.clearRect(0, 0, cvs.width, cvs.height) to clear the entire canvas);

6. Polygon

Drawing polygons requires the combination of moveTo(), lineTo(), and closePath();

7. Circle (arc)

The method of drawing a circle is arc(); (drawing a curve bezierCurveTo())

arc(x, y, r, sAngle, eAngle,counterclockwise)
// x, y 是圆心坐标
// sAngle, eAngle是开始角度 结束角度(以弧度为单位。例如 180°就写成 Math.PI ,360°写成 Math.PI * 2 )
// counterclockwise 绘制方向,默认false(true: 逆时针,false: 顺时针)

Note: The beginPath() method must be called before drawing a circle; the closePath() method must be called after drawing;

let cvs = document.getElementById('cvs')
let ctx = cvs.getContext('2d');

ctx.beginPath();
ctx.arc(100, 100, 50, 0, 360 * Math.PI / 180, false);
ctx.closePath(); // 不调用closePath()就可以绘制弧线
ctx.stroke();

insert image description here

8. Text

You can set the text style, stroke, fill, alignment, etc.

style: font

cxt.font = 'font-style font-variant font-weight font-size/line-height font-family'

Stroke: strokeText()

/** 
text: 要描边的文本
x: 横坐标,文本左边要对齐的坐标
y: 纵坐标, 文本底部要对齐的坐标
maxWidth: 可选,文本最大渲染宽度,超出文本会被压缩
**/
strokeText(text, x, y, maxWidth)

Filling: fillText() syntax is the same as stroke

<canvas id="canvas"></canvas>
<script>
let cvs = document.getElementById('canvas')
let ctx = cvs.getContext('2d'); // 获取webgl上下文
ctx.font = '40px Arial'
ctx.strokeStyle = 'red' // 设置描边颜色
ctx.strokeText('hello', 100, 100)

ctx.fillStyle = 'black' // 设置填充颜色
ctx.fillText('hello', 100, 100)

</script>

insert image description here

Calculate text width: measureText(text)

ctx.measureText('hello world!').width
9. Pictures

Can be used to render pictures, set picture width and height, capture pictures, etc.

Render the image:

语法: 
// image: 图片对象 
// ltx: 图片左上角的横坐标位置
// lty: 图片左上角的纵坐标位置
drawImage(image, ltx, lty)  
<canvas id="canvas" width="1500" height="1500"></canvas>
<script>
    let cvs = document.getElementById('canvas')
    let ctx = cvs.getContext('2d'); // 获取webgl上下文

    const image = new Image(); // 1. 创建image对象
    image.src = './微信图片_20220620163205.png'// 2. 引入图片
    image.onload = () => {
    
     // 3. 加载图片
    	ctx.drawImage(image, 100, 100); // 使用drawImage()方法渲染
	}
</script>

Set the width and height of the picture : just add two more parameters~

drawImage(image, ltx, lty, w, h); // w h分别表示图片宽高

**Intercept picture:** There are more parameters, and the order has changed

// sx, sy, sw, sh分别表示: 开始截取的横坐标、纵坐标,截取的宽高
drawImage(image, sx, sy, sw, sh, ltx, lty, w, h)
ctx.drawImage(image, 50, 300, 300, 300, 200, 200, 200, 200);

insert image description hereinsert image description here

10. Gradient:

Linear Gradient: createLinearGradient(x1, y1, x2, y2)

Radial Gradient: createRadialGradient(x1, y1, r1, x2, y2, r2)

Steps to create a linear gradient:

​ a. Use the createLinearGradient() method to create a CanvasGradient object that specifies the start and end points (two points determine a straight line);

b. Use the addColorStop() method on the CanvasGradient object to add a starting color stop;

c. Assign the CanvasGradient object to the strokeStyle or fillStyle attribute;

let cvs = document.getElementById('canvas')
let ctx = cvs.getContext('2d'); // 获取canvas 平面 上下文

var gradient = ctx.createLinearGradient(0,0,200,0); // 步骤a
gradient.addColorStop(0,"green"); // 步骤b
gradient.addColorStop(1,"blue");
ctx.fillStyle = gradient; // 步骤c
ctx.fillRect(10,10,200,100);

The above are just some basic syntax of canvas, as well as advanced gameplay such as projection and filter;

For more detailed syntax, please refer to: https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D

Guess you like

Origin blog.csdn.net/weixin_53058401/article/details/128705218