三、平移

三、平移

3.1 translate

使用方式:

ctx.translate(x, y)

1
2
// 将坐标系原点平移到canvas的中心
ctx.translate(canvas.width / 2, canvas.height / 2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 获取元素
var canvas = document.getElementById("myCanvas");
// 获取画笔
var ctx = canvas.getContext("2d");

// 在canvas中心绘制圆
drawCircle(canvas.width / 2, canvas.height / 2, 50);

// 平移坐标系 将原点改为canvas的中心
ctx.translate(canvas.width / 2, canvas.height / 2);

// 再次绘制圆
drawCircle(0, 0, 20);

// 在平移坐标系之前绘制了一个圆,在平移坐标系之后又绘制了一个圆
// 在平移坐标系之前绘制的图形不会因该坐标系的改变而改变

// 封装一个函数,用于绘制圆
function drawCircle(x, y, r){
// 开启路径
ctx.beginPath();
// 绘制圆
ctx.arc(x, y, r, 0, Math.PI * 2);
// 闭合路径
ctx.closePath();
// 描边
ctx.stroke();
}

UYcXqO.png

3.2 平移坐标系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 获取元素
var canvas = document.getElementById("myCanvas");
// 获取画笔
var ctx = canvas.getContext("2d");

// 平移坐标系之前绘制坐标轴
drawXY();

// 平移坐标系
ctx.translate(canvas.width / 2, canvas.height / 2);

// 再次绘制坐标轴
drawXY();

// 封装函数,传递两个点,绘制两个点之间的线段
function line(x1, y1, x2, y2){
// 开启路径
ctx.beginPath();
// 移动画笔到某个位置
ctx.moveTo(x1, y1);
// 绘制路径
ctx.lineTo(x2, y2);
// 关闭路径
ctx.closePath();
// 描边
ctx. stroke();
}

// 封装函数,绘制坐标系
function drawXY(){
// 绘制 x 轴
line(5, 5, 590, 5);
line(585, 0, 590, 5);
line(585, 10, 590, 5);
line(100, 0, 110, 5);
line(100, 10, 110, 5);
// 绘制 y 轴
line(5, 5, 5, 390);
line(0, 385, 5, 390);
line(10, 385, 5, 390);
line(0, 100, 5, 110);
line(10, 100, 5, 110);
}

UYczIH.png

3.3 rotate 旋转

使用方式:

1
2
ctx.rotate(deg)
deg:角度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 获取元素
var canvas = document.getElementById("myCanvas");
// 获取画笔
var ctx = canvas.getContext("2d");

// 平移坐标系之前绘制坐标轴
// drawXY();

// 平移坐标系
ctx.translate(canvas.width / 2, canvas.height / 2);

// 再次绘制坐标轴
drawXY();

// 定义角度
var deg = Math.PI / 180;

// 开启定时器
var timer = setInterval(function(){
// 清屏 坐标轴原点现在是在中心 要覆盖整个canvas,需要时负值
ctx.clearRect(-canvas.width, -canvas.height, 3000, 3000);
ctx.rotate(deg);
drawXY();
}, 20);

// 封装函数,传递两个点,绘制两个点之间的线段
function line(x1, y1, x2, y2){
// 开启路径
ctx.beginPath();
// 移动画笔到某个位置
ctx.moveTo(x1, y1);
// 绘制路径
ctx.lineTo(x2, y2);
// 关闭路径
ctx.closePath();
// 描边
ctx. stroke();
}

// 封装函数,绘制坐标系
function drawXY(){
// 绘制 x 轴
line(5, 5, 590, 5);
line(585, 0, 590, 5);
line(585, 10, 590, 5);
line(100, 0, 110, 5);
line(100, 10, 110, 5);
// 绘制 y 轴
line(5, 5, 5, 390);
line(0, 385, 5, 390);
line(10, 385, 5, 390);
line(0, 100, 5, 110);
line(10, 100, 5, 110);
}

UYgPzt.png

点击查看

本文标题:三、平移

文章作者:Mango

发布时间:2020年07月14日 - 13:22:39

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/f43e1d68.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------