-
Notifications
You must be signed in to change notification settings - Fork 0
/
09polygonclippingsutherlandhodgman.html
77 lines (68 loc) · 2.16 KB
/
09polygonclippingsutherlandhodgman.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sutherland-Hodgman</title>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<canvas id="container" width="800" height="800"></canvas>
<script>
var subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];
var clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
var context;
draw();
function draw() {
var canvas = document.getElementById("container");
context = canvas.getContext("2d");
context.strokeStyle = "rgba(255, 0, 0, 1.0)";
context.strokeRect(100, 100, 200, 200);
var clippedPolygon = clip(subjectPolygon, clipPolygon);
drawPolygon(context, clipPolygon, "red");
drawPolygon(context, subjectPolygon, "blue");
drawPolygon(context, clippedPolygon, "black", "green");
}
function clip(subjectPolygon) {
var clipA, clipB, vertexP, vertexQ;
var outputList = subjectPolygon;
clipA = clipPolygon[clipPolygon.length-1];
for (var i in clipPolygon) {
clipB = clipPolygon[i];
var inputList = outputList;
outputList = [];
vertexP = inputList[inputList.length - 1];
for (var j in inputList) {
vertexQ = inputList[j];
if (inside(clipA, clipB, vertexQ)) {
if (!inside(clipA, clipB, vertexP)) {
outputList.push(intersection(clipA, clipB, vertexP, vertexQ));
}
outputList.push(vertexQ);
}
else if (inside(clipA, clipB, vertexP)) {
outputList.push(intersection(clipA, clipB, vertexP, vertexQ));
}
vertexP = vertexQ;
}
clipA = clipB;
}
return outputList
}
function inside(a, b, p) {
return (b[0]-a[0])*(p[1]-a[1]) > (b[1]-a[1])*(p[0]-a[0]);
}
function intersection(a, b, p, q) {
var A1 = b[1] - a[1];
var B1 = a[0] - b[0];
var C1 = A1 * a[0] + B1 * a[1];
var A2 = q[1] - p[1];
var B2 = p[0] - q[0];
var C2 = A2 * p[0] + B2 * p[1];
var det = A1 * B2 - A2 * B1;
var x = (B2 * C1 - B1 * C2) / det;
var y = (A1 * C2 - A2 * C1) / det;
return [x, y];
}
</script>
</body>
</html>