-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
140 lines (127 loc) · 3.78 KB
/
index.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<style type="text/css">
body {
margin: 0;
padding: 0;
}
.container{
width:100%;
height:100vh;
background-image:url('./images/bg.jpg');
background-size: cover;
position:relative;
}
#myCanvas{
position:absolute;
top:0;
left:0;
z-index:1;
cursor: crosshair;
}
.mask{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
z-index:10;
display:none;
background-color:rgba(0,0,0,0.8);
}
#pic{
position:absolute;
top:50%;
left:50%;
}
</style>
</head>
<body>
<div class="container">
<div class="mask">
<canvas id="pic"></canvas>
</div>
<canvas id="myCanvas" width="1000" height="600"></canvas>
</div>
<script>
var cont = document.getElementsByClassName("container")[0];
var mask = document.getElementsByClassName("mask")[0];
// 截图框
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
// 截图完后存放图片
var c2 = document.getElementById('pic');
var ctxPic = c2.getContext('2d');
// 鼠标按下标志
var isDown = false;
var x0, y0, x1, y1;
var image = new Image();
var temp;
image.src = "./images/bg.jpg";
c.onmousedown = function (event) {
event = event ? event : window.event;
isDown = true;
x0 = event.pageX;
y0 = event.pageY;
}
c.onmousemove = function (event) {
event = event ? event : window.event;
if (isDown) {
// 画截图框(矩形)
ctx.clearRect(0, 0, c.width, c.height);
x1 = event.pageX;
y1 = event.pageY;
drawLine(x0, y0, x1, y0); //上
drawLine(x0, y0, x0, y1); //左
drawLine(x1, y1, x1, y0); //右
drawLine(x1, y1, x0, y1); //下
}
}
c.onmouseup = function () {
if (isDown) {
ctx.clearRect(0, 0, c.width, c.height);
isDown = false;
mask.style.display = "block";
//鼠标释放的时候,画出来的形状是个矩形,保持x0,y0是左上角的坐标,x1,y1是右下角的坐标
if (x0 > x1) {
temp = x0;
x0 = x1;
x1 = temp;
}
if (y0 > y1) {
temp = y0;
y0 = y1;
y1 = temp;
}
playCutPic(x0, y0, x1, y1);
}
}
mask.onclick = reset;
function reset()
{
ctx.clearRect(0, 0, c.width, c.height);
ctxPic.clearRect(0, 0, c.width, c.height);
mask.style.display = "none";
}
function playCutPic(x0,y0,x1,y1) {
c2.width = x1 - x0;
c2.height = y1 - y0;
c2.style.marginTop = -c2.height / 2 + 'px';
c2.style.marginLeft = -c2.width / 2 + 'px';
ctxPic.drawImage(image, x0, y0, x1 - x0, y1 - y0,
0, 0, c2.width, c2.height);
}
function drawLine(x1, y1, x2, y2) {
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = 'white';
ctx.stroke();
}
</script>
</body>
</html>