1,矩形
矩形有三种:
- 轮廓,画四条边。
- 填充,画一个矩形区域。
- 清除,让一个矩形区域完全透明。
举例:
填充绿色。
清除一片。
轮廓红色。
pen.fillStyle = 'green';
pen.fillRect(0, 0, 300, 300);
pen.clearRect(50, 50, 200, 200);
pen.strokeStyle = 'red';
pen.strokeRect(100, 100, 100, 100);
效果:
2,路径
绘制一个路径的基本过程:
- 开启路径,beginPath()
- 一通操作
- 闭合路径,closePath()
- 选择,轮廓还是填充。stroke(),fill()
PS:填充的路径,会自动闭合。
也可以手动画到闭合的点来闭合。
举例:三角形
pen.beginPath();
pen.moveTo(150, 0);
pen.lineTo(0, 150);
pen.lineTo(150, 300);
pen.fill();
pen.beginPath();
pen.moveTo(300, 0);
pen.lineTo(150, 150);
pen.lineTo(300, 300);
pen.closePath();
pen.stroke();
移动
moveTo(x, y)
直线
lineTo(x, y)
圆弧
arc(x, y, radius, startAngle, endAngle, anticlockwise)
圆心,半径,开始角度,结束角度。
可选,是否逆时针。默认false顺时针。
pen.beginPath();
pen.arc(150, 150, 150, 0, Math.PI)
pen.fill();
效果:顺时针0到π。
arcTo(x1, y1, x2, y2, radius)
比较复杂,由两点一角来定圆弧。
有三个点:
起始点M,
A,x1y1
B。x2y2
一个半径。
MA与AB,垂线交点为圆心。半径。
pen.beginPath();
pen.moveTo(0, 0)
pen.arcTo(300, 0, 300, 300, 300)
pen.stroke();
效果:
半径不足会:
贝塞尔
quadraticCurveTo(cp1x, cp1y, x, y)
一个控制点,一个结束点。
pen.beginPath();
pen.moveTo(0, 0)
pen.quadraticCurveTo(300, 0, 300, 300)
pen.stroke();
效果:
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
两个控制点,一个结束点。
pen.beginPath();
pen.moveTo(0, 0)
pen.bezierCurveTo(300, 0, 300, 300, 0, 300)
pen.stroke();
效果:
也有起始点。
矩形
rect(x, y, width, height)
走一圈,又回到最初的起点。
pen.beginPath();
pen.rect(50, 50, 200, 200)
pen.fill();
效果:
3,Path2D
为复用而生。所有的路径操作都可以对它使用。
不需要开启,也不需要关闭。
简单使用:
function draw(pen) {
let a=new Path2D();
a.rect(50, 50, 200, 200)
pen.fill(a);
}
效果: