html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style>
div{
text-align: center;
}
canvas{
background-color: white;
position: absolute;
}
#cv1{
border:1px solid #000000;
z-index: 1;
}
#cv2{
z-index: 2;
left:0px;
top:0px;
border: thin dashed black;
border-radius: 40px;
-moz-border-radius:40px;
-o-border-radius:40px;
-webkit-border-radius:40px;
display: none;
position: relative;
}
</style>
</head>
<body>
<div>
<h1>放大镜</h1>
<canvas id = "cv1" width = "720px" height = "500px"></canvas>
<canvas id = "cv2" width = "100px" height = "100px"></canvas>
</div>
<script src = "myjs1.js"></script>
</body>
</html>
js
var canvas1 = document.getElementById("cv1");
var canvas2 = document.getElementById("cv2");
var ctx = canvas1.getContext('2d');
var image = new Image();
window.onload = function() {
image.src = "girl.jpg"
image.onload = function(){
ctx.drawImage(image,0,0,canvas1.width,canvas1.height);
}
canvas1.onmousemove = canvas1_onmouse_move;
canvas1.onmouseout = canvas1_onmouse_out;
}
function canvas1_onmouse_move(ev) {
var x,y;
var drawWidth,drawHeight;
var ctx2 = canvas2.getContext('2d');
canvas2.style.display = "inline";
ctx2.clearRect(0,0,canvas2.width,canvas2.height);
x = ev.pageX - canvas1.offsetLeft;
y = ev.pageY - canvas1.offsetTop;
canvas2.style.left = x+2+"px";
canvas2.style.top = y+2+"px";
if (x+100>canvas1.width) {
drawWidth = canvas1.width -x;
}else {
drawWidth = 100;
}
if (y+100 > canvas1.height) {
drawHeight = canvas1.height -y;
}else{
drawHeight = 100;
}
ctx2.drawImage(image,x,y,drawWidth,drawHeight,0,0,drawWidth,drawHeight);
}
function canvas1_onmouse_out(){
canvas2.style.display = "none";
}