没有一朵花,从一开始就是花。
目录
- translate() 方法:
- rotate() 方法:
- scale() 方法:
translate() 方法:
Canvas 2D API 的 CanvasRenderingContext2D.translate() 方法用于对当前网格添加平移变换。
translate() 方法通过在网格上将画布和原点水平移动 x 单位和垂直移动 y 单位,向当前矩阵添加一个平移变换。
移动画板的坐标系的原点(不是移动画板)
translate(x, y)
上图为网络截取,侵权联系删除。
- x:在水平方向上移动的距离。正值向右移动,负值向左移动。
- y:在垂直方向上移动的距离。正值向下移动,负值向上移动。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>translate属性</title>
</head>
<body>
<canvas id="canvas" width="550" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 移动的正方形
ctx.translate(110, 30);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 80, 80);
// 重置当前的变换矩阵为单位矩阵
ctx.setTransform(1, 0, 0, 1, 0, 0);
// 未移动的正方形
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, 80, 80);
</script>
</body>
</html>
rotate() 方法:
Canvas 2D API 的 CanvasRenderingContext2D.rotate() 方法用于在变换矩阵中增加旋转。
rotate(angle)
- angle:顺时针旋转的弧度。如果你想通过角度值计算,可以使用公式: degree * Math.PI / 180 。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>rotate属性</title>
</head>
<body>
<canvas id="canvas" width="550" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 变换原点
ctx.arc(0, 0, 5, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
// 未旋转的矩形
ctx.fillStyle = "gray";
ctx.fillRect(100, 0, 80, 20);
// 旋转的矩形
ctx.rotate((45 * Math.PI) / 180);
ctx.fillStyle = "red";
ctx.fillRect(100, 0, 80, 20);
// 将变换矩阵重置为单位矩阵
ctx.setTransform(1, 0, 0, 1, 0, 0);
</script>
</body>
</html>
scale() 方法:
Canvas 2D API 的 CanvasRenderingContext2D.scale() 方法用于根据水平和垂直方向,为 canvas 单位添加缩放变换。
官方解释:
默认情况下,在 canvas 中一个单位实际上就是一个像素。例如,如果我们将 0.5 作为缩放因子,最终的单位会变成 0.5 像素,并且形状的尺寸会变成原来的一半。相似的方式,我们将 2.0 作为缩放因子,将会增大单位尺寸变成两个像素。形状的尺寸将会变成原来的两倍。
scale(x, y)
- x:水平方向的缩放因子。负值会将像素沿垂直轴翻转。值为 1 表示没有水平缩放。
- y:垂直方向的缩放因子。负值会将像素沿水平轴翻转。值为 1 表示没有垂直缩放。
- 无返回值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>scale</title>
</head>
<body>
<canvas id="canvas" width="550" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 缩放后的矩形
ctx.scale(9, 3);
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 8, 20);
// 将当前变换矩阵重置为单位矩阵
ctx.setTransform(1, 0, 0, 1, 0, 0);
// 未缩放的矩形
ctx.fillStyle = "gray";
ctx.fillRect(10, 10, 8, 20);
</script>
</body>
</html>