-
Notifications
You must be signed in to change notification settings - Fork 0
/
2drotate.html
122 lines (112 loc) · 2.48 KB
/
2drotate.html
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
</head>
<body>
<div class="main">
<canvas id="canvas" width="600" height="400"></canvas>
</div>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = ctx.stokeStyle = '#ccc';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var rect1 = {
x : 100,
y : 200,
width : 100,
height : 100,
angle : 45
};
var rect2 = {
x : 150,
y : 150,
width : 50,
height : 120,
angle : 60
};
/*function drawRect (obj) {
var x = obj.x,
y = obj.y,
w = obj.width,
h = obj.height,
angle = Math.PI * (obj.angle / 180);
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#000';
ctx.translate(x + w / 2, y + h / 2);
ctx.rotate(angle);
ctx.rect(-w / 2, -h / 2, w, h);
ctx.translate(-x - w / 2, -y - h / 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
ctx.save();
drawRect(rect1);
drawRect(rect2);*/
rotateRect(rect1);
function rotateRect(obj) {
// 画出未旋转的图形
ctx.fillStyle = '#000';
ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
var points = [
{
x : -obj.width / 2,
y : -obj.height / 2
},
{
x : obj.width / 2,
y : -obj.height / 2
},
{
x : obj.width / 2,
y : obj.height / 2
},
{
x : -obj.width / 2,
y : obj.height / 2
}
];
var centerPoint = {
x : obj.x + obj.width / 2,
y : obj.y + obj.height / 2
};
var resPoint = [];
for (var i = 0 ; i < points.length; i++) {
var point = points[i];
var pointTmp = getRotatePointPos(point, obj.angle);
resPoint.push({x : pointTmp.x + centerPoint.x, y : pointTmp.y + centerPoint.y});
}
ctx.fillStyle = '#f00';
ctx.beginPath();
for (var j = 0; j < resPoint.length; j++) {
var point = resPoint[j];
ctx.lineTo(point.x, point.y);
}
ctx.closePath();
ctx.fill();
return resPoint;
}
function getRotatePointPos (point, angle) {
var matrix = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 1]
];
var cos = Math.cos,
sin = Math.sin,
angle = angle / 180 * Math.PI;
matrix[0][0] = cos(angle);
matrix[0][1] = sin(angle);
matrix[1][0] = -sin(angle);
matrix[1][1] = cos(angle);
var res = {};
res.x = point.x * cos(angle) - point.y * sin(angle);
res.y = point.x * sin(angle) + point.y * cos(angle);
return res;
}
</script>
</body>
</html>