<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鼠标事件</title>
</head>
<body>
<canvas id="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 isMouseDown=false;
//定义缩放值
var scale
window.οnlοad=function(){
canvas.width="1030";
canvas.height='750';
image.src="timg.jpg"
//图片的原始尺寸要大于canvas的尺寸
image.οnlοad=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)
}
//将屏幕的坐标转换为在canvas的坐标
function windowToCanvas(x,y){
//获取canvas距离浏览器周围的left和top值
var bbox=canvas.getBoundingClientRect();
return {x:x-bbox.left,y:y-bbox.top}
}
//鼠标按下
canvas.οnmοusedοwn=function(e){
e.preventDefault(e);
var point=windowToCanvas(e.clientX,e.clientY);
//console.log('point.left'+point.x+','+e.clientX+','+e.clientY)
isMouseDown=true
//绘制放大镜 当onmouseup、onmouseout时 drawcanvasWithMagnifier传入false
drawcanvasWithMagnifier(true,point)
}
//鼠标移动
canvas.οnmοusemοve=function(e){
e.preventDefault(e);
//需要查看鼠标的左键是否点击着 如果没有点击则释放放大镜效果
//isMouseDown为true时显示放大镜
if(isMouseDown){
var point=windowToCanvas(e.clientX,e.clientY);
//console.log('point.left'+point.x+','+e.clientX+','+e.clientY)
drawcanvasWithMagnifier(true,point)
}
}
//鼠标松开
canvas.οnmοuseup=function(e){
e.preventDefault(e);
isMouseDown=false;
drawcanvasWithMagnifier(false)
}
//鼠标移开
canvas.οnmοuseοut=function(e){
e.preventDefault(e);
isMouseDown=false;
drawcanvasWithMagnifier(false)
}
function drawcanvasWithMagnifier(isMouseDown,point){
context.clearRect(0,0,canvas.width,canvas.height)
context.drawImage(image,0,0,canvas.width,canvas.height);
if(isMouseDown){
//绘制放大镜】
drawMagnifier(point)
}
}
function drawMagnifier(point){
//console.log('point.x'+point.x+'point.y'+point.y);
//鼠标点击的位置 计算出在放大图像中的位置 计算出大图的中心坐标
var imageLG_cx=point.x*scale
var imageLg_cy=point.y*scale
//放大镜显示的大小 设置为200 放大镜的半径为200
var mr=200
//计算圆形的坐标和宽高
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.0;
context.strokeStyle='#069'
context.beginPath()
//圆形剪辑
context.arc(point.x,point.y,mr,0,Math.PI*2)
context.stroke();
context.clip();
context.drawImage(offcanvas,sx,sy,2*mr,2*mr,dx,dy,2*mr,2*mr);
context.restore()
}
}
</script>
</body>
</html>