Appearance
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
<img src="./imgs/path-api.png" alt="">
<img src="./imgs/nonzero-winding-rule.png" alt="">
<script>
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
canvas.width = 1000
canvas.height = 700
context.font = '32pt Arial'
context.strokeStyle = 'blue'
context.fillStyle = 'red'
context.lineWidth = '2'
// 文本描边和填充
context.strokeText('Stroke', 60, 60)
context.fillText('Fill', 400, 60)
context.strokeText('Stroke & Fill', 660, 60)
context.fillText('Stroke & Fill', 660, 60)
// 长方形 rect创建的路径是封闭的
context.lineWidth = '5'
context.beginPath()
context.rect(50, 150, 150, 100)
context.stroke()
context.beginPath()
context.rect(350, 150, 150, 100)
context.fill()
context.beginPath()
context.rect(700, 150, 150, 100)
context.stroke()
context.fill()
// 开放路径下 arc 创建的圆弧路径不封闭,除非你创建的是个圆形路径,要封闭某段路径,
// 必须调用closePath()
context.beginPath()
/**
* 绘制圆弧路径的方法
*
* @param {number} x 圆弧中心(圆心)的 x 轴坐标。
* @param {number} y 圆弧中心(圆心)的 y 轴坐标。
* @param {number} radius 圆弧的半径。
* @param {number} startAngle 圆弧的起始点, x 轴方向开始计算,单位以弧度表示。
* @param {number} endAngle 圆弧的终点, 单位以弧度表示。
* @param {boolean=false} anticlockwise 可选的 Boolean 值 ,如果为 true,
* 逆时针绘制圆弧,反之,顺时针绘制。
*/
context.arc(125, 370, 60, 0, Math.PI * 3 / 2)
context.stroke()
context.beginPath()
context.arc(420, 370, 60, 0, Math.PI * 3 / 2)
context.fill()
context.beginPath()
context.arc(770, 370, 60, 0, Math.PI * 3 / 2)
context.stroke()
context.fill()
// 封闭路径
context.beginPath()
context.arc(125, 540, 60, 0, Math.PI * 3 / 2)
context.closePath()
context.stroke()
context.beginPath()
context.arc(420, 540, 60, 0, Math.PI * 3 / 2)
context.closePath()
context.fill()
context.beginPath()
context.arc(770, 540, 60, 0, Math.PI * 3 / 2)
context.closePath()
context.stroke()
context.fill()
// 在某一时刻,canvas 中只能有一条路径存在,称为“当前路径”,这条路径却可以包含许多
// 子路径,而子路径,又是由两个或更多点组成的。
const canvas2 = document.querySelector('#canvas2')
const context2 = canvas2.getContext('2d')
context2.beginPath()
// 创建包含矩形四个点的子路经
context2.rect(10, 50, 50, 50)
context2.strokeStyle = 'red'
context2.stroke()
// context2.beginPath()
// 没有调用beginPath方法清除原有子路径,因此会向当前路径中再增加一条子路径
context2.rect(70, 50, 50, 50)
context2.strokeStyle = 'green'
// 会使得当前路径的两个子路径都被描边,意味着它会重绘第一个矩形,第一个矩形也变成了绿色。
context2.stroke()
</script>
</body>
</html>