-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathimg-magnifier.html
116 lines (93 loc) · 3.37 KB
/
img-magnifier.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片查看器</title>
</head>
<body style="background: black;">
<canvas id="canvas" style="display:block;margin:0 auto;border:1px solid #aaa;">您的浏览器尚不支持canvas</canvas>
<canvas id="offCanvas" style="display: none">
</canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var offCanvas = document.getElementById('offCanvas');
var offContext = offCanvas.getContext('2d');
var image = new Image();
var scale;
var isMouseDown = false;
window.onload = function () {
canvas.width = 1152;
canvas.height = 768;
image.src = 'src/img-lg.jpg';
image.onload = function () {
offCanvas.width = image.width;
offCanvas.height = image.height;
scale = offCanvas.width/canvas.width;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
offContext.drawImage(image,0,0)
}
}
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect();
return {
x: x - bbox.left,
y: y - bbox.top
}
}
canvas.onmousedown = function (e) {
e.preventDefault()
isMouseDown = true;
point = windowToCanvas(e.clientX, e.clientY);
drawCanvasWithMagnifier(true, point)
}
canvas.onmouseup = function (e) {
e.preventDefault()
isMouseDown = false;
drawCanvasWithMagnifier(false);
}
canvas.onmouseout = function (e) {
e.preventDefault()
isMouseDown = false
drawCanvasWithMagnifier( false )
}
canvas.onmousemove = function (e) {
e.preventDefault()
if(isMouseDown){
point = windowToCanvas(e.clientX,e.clientY);
drawCanvasWithMagnifier(true,point);
}
}
function drawCanvasWithMagnifier(isShowMagnifier, point) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
if (isShowMagnifier) {
drawMagnifier(point);
}
}
function drawMagnifier(point) {
var mr = 200;
//将缩小版图片上点击的位置映射到大图上
var imageLG_cx = point.x*scale;
var imageLG_cy = point.y*scale;
//将大图上对应的点移动到圆心
var sx = imageLG_cx - mr;
var sy = imageLG_cy - mr;
var dx = point.x - mr;
var dy = point.y - mr;
context.save();
context.lineWidth=10;
context.strokeStyle='#069';
context.beginPath();
context.arc(point.x, point.y, mr,0, 2*Math.PI, false);
context.stroke();
context.clip();
context.drawImage(offCanvas, sx, sy, 2*mr, 2*mr,dx,dy,2*mr,2*mr);
context.closePath();
context.restore();
}
</script>
</body>
</html>