Canvas introduction and basic use
1. Introduction to Canvas
canvas is a new tag in HTML5, which can use JavaScript to draw various patterns.
2. The difference between Canvas and SVG
- svg is essentially a language for describing 2D graphics using XML
1. Each element created by svg is an independent DOM element, which can be manipulated by css and JS.
2. Modify the DOM elements in the svg, and the system will automatically redraw the DOM.
- Canvas draws 2D graphics through JavaScript
1. Canvas is just an HTML element, and the graphics in it will not create DOM elements separately, so the individual graphics in Canvas cannot be manipulated through JS.
2. Once the graph is drawn, it needs to be redrawn if the data changes.
- scenes to be used
If the amount of data to be displayed is relatively large, for example, a piece of data is an element node, then it is more appropriate to use canvas;
if there are many user interactions and there is a requirement for clarity (vector diagram), then it is more appropriate to use svg.
3. Basic use of Canvas
3.1 Create Canvas
<!DOCTYPE html>
<html lang="en">
<head>
<title>canvas 基本使用</title>
</head>
<body>
<canvas width="200" height="200">
当前浏览器不支持canvas元素,请升级或更换浏览器!
</canvas>
</body>
</html>
- Effect
- canvas size
canvas The default canvas size is 300 * 150.
There are two options for resizing the canvas:
First way : styling via css (not recommended)
<html>
<head>
<style>
canvas {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
</html>
Using CSS to define the size, the image will stretch when drawn: if the CSS size does not match the ratio of the initial canvas, it will appear distorted.
For example, if this example becomes 400px * 400px, then the width will be stretched from 300px to 400px, and the height will be stretched from 150px to 400px.
Second way : via tag attribute (recommended)
<html>
<head>
...
</head>
<body>
<canvas width="400" height="400"></canvas>
</body>
</html>
Therefore, use the width and height attributes provided by the canvas element to set the width and height of the canvas.
3.2 Rendering context
After creating a Canvas canvas, the next step is to get the context environment of the Canvas, and get the rendering context and painting function through getContext().
<body>
<canvas id="canvas"></canvas>
<script>
// 获取canvas元素
var canvas = document.getElementById('canvas');
// 获取二维渲染上下文
var ctx = canvas.getContext('2d');
</script>
</body>
context type:
- 2d: Create a two-dimensional rendering context.
- webgl: Create a WebGLRenderingContext 3D rendering context object.
- webgl2: Creates a WebGL2RenderingContext 3D rendering context object; only available on browsers that implement WebGL version 2 (OpenGL ES 3.0).
3.3 Canvas coordinates
Canvas uses the W3C coordinate system, that is, it follows the reading habits of our screens and newspapers, from top to bottom, from left to right, and the upper left corner is the origin.
3.4 Draw a straight line
The easiest is to draw a straight line.
These 3 methods need to be used:
- moveTo(x, y): Set the initial position.
- lineTo(x, y): The coordinates (x, y) of the next point.
- stroke(): Draw the outline of the graphic through lines.
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取 canvas 元素
var canvas = document.getElementById('canvas');
// 获取绘图上下文
var ctx = canvas.getContext('2d');
// 绘制直线
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.stroke();
</script>
3.5 Drawing triangles
Draw two triangles, one filled and the other stroked.
The method that needs to be used:
- beginPath(): Create a new path.
- closePath(): Closes the path.
- stroke(): Draw the outline of the graphic through lines.
- fill(): Generates a solid shape by filling the content area of the path.
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取 canvas 元素
var canvas = document.getElementById('canvas');
// 获取绘图上下文
var ctx = canvas.getContext('2d');
// 填充三角形
ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(105, 25);
ctx.lineTo(25, 105);
ctx.fill();
// 描边三角形
ctx.beginPath();// 重新开启一个路径
ctx.moveTo(125, 125);
ctx.lineTo(125, 45);
ctx.lineTo(45, 125);
ctx.closePath();
ctx.stroke();
</script>
beginPath() reopens a path, and the following line segments will not affect the previous line segments.
When using fill (fill), the path is automatically closed, and using stroke (stroke) does not close the path. If the closed path closePath() is not added to the stroke triangle function, only two line segments are drawn, not a complete triangle.
3.6 Drawing a rectangle
Line segments can be used to draw rectangles, but canvas also provides methods such as rect() to directly generate rectangles.
- Use strokeRect() to stroke a rectangle
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.strokeStyle = 'pink'
ctx.strokeRect(50, 50, 200, 100) // strokeRect(x, y, width, height)
</script>
- Use fillRect() to fill the rectangle
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'pink'
ctx.fillRect(50, 50, 200, 100) // fillRect(x, y, width, height)
</script>
- Use rect() to generate a rectangle
Note: After the rect() method is called, you need to call stroke() or fill() to assist rendering.
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.strokeStyle = 'red'
ctx.fillStyle = 'pink'
ctx.rect(50, 50, 200, 100) // rect(x, y, width, height)
ctx.stroke()
ctx.fill()
</script>
- Use clearRect() to clear the rectangle
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'pink' // 设置填充颜色
ctx.fillRect(50, 50, 200, 200) // 填充矩形
ctx.clearRect(60, 60, 180, 90) // 清空矩形
</script>
3.7 Drawing text
grammar:
ctx.font = 'font-style font-variant font-weight font-size/line-height font-family'
- The strokeText() method draws stroked text
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.font = '60px Arial'
cxt.strokeStyle = 'pink' // 设置文本描边颜色
ctx.strokeText('好运', 30, 90) //strokeText(text, x, y, maxWidth)
</script>
- fillText() draws filled text
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.font = '60px Arial'
ctx.font = '60px Arial'
ctx.fillStyle = 'pink'
ctx.fillText('好运', 30, 90)
</script>
- textAlign sets the horizontal alignment of the text
1. start: default. Start at the abscissa of the specified position.
2.end: End at the abscissa of the specified coordinate.
3.left: left alignment.
4.right: Right alignment.
5.center: Center alignment.
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
// 参考线
ctx.moveTo(200, 0)
ctx.lineTo(200, 400)
ctx.strokeStyle = 'red'
ctx.stroke()
ctx.font = '30px Arial'
// 横坐标开始位对齐
ctx.textAlign = 'start' // 默认值,
ctx.fillText('好运start', 200, 40)
// 横坐标结束位对齐
ctx.textAlign = 'end' // 结束对齐
ctx.fillText('好运end', 200, 100)
// 横坐标开始位对齐
ctx.textAlign = 'left' // 默认值,
ctx.fillText('好运start', 200, 160)
// 横坐标结束位对齐
ctx.textAlign = 'right' // 结束对齐
ctx.fillText('好运end', 200, 220)
// 居中对齐
ctx.textAlign = 'center' // 右对齐
ctx.fillText('好运center', 200, 280)
</script>
- textBaseline sets the vertical alignment of the text
1. Alphabetic: Default. The text baseline is an ordinary letter baseline.
2.top: The text baseline is the top of the em box.
3.bottom: The text baseline is the bottom of the em box.
4.middle: The text baseline is the middle of the em box.
5.hanging: The text baseline is a hanging baseline.
<canvas id="canvas" width="800" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
// 参考线
ctx.moveTo(0, 150)
ctx.lineTo(800, 150)
ctx.strokeStyle = 'red'
ctx.stroke()
ctx.font = '20px Arial'
// 默认 alphabetic
ctx.textBaseline = 'alphabetic'
ctx.fillText('好运alphabetic', 10, 150)
// 默认 top
ctx.textBaseline = 'top'
ctx.fillText('好运top', 200, 150)
// 默认 bottom
ctx.textBaseline = 'bottom'
ctx.fillText('好运bottom', 320, 150)
// 默认 middle
ctx.textBaseline = 'middle'
ctx.fillText('好运middle', 480, 150)
// 默认 hanging
ctx.textBaseline = 'hanging'
ctx.fillText('好运hanging', 640, 150)
</script>
3.8 Drawing pictures
Use the drawImage() method to draw pictures, syntax:
drawImage(image, dx, dy)
- image: The image object to render.
- dx: The abscissa position of the upper left corner of the image.
- dy: The ordinate position of the upper left corner of the image.
<canvas id="canvas" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
<script>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
// 1 创建 Image 对象
const image = new Image()
// 2 引入图片
image.src = './images/hz.png'
// 3 等待图片加载完成
image.onload = () => {
// 4 使用 drawImage() 方法渲染图片
ctx.drawImage(image, 30, 30)
}
</script>