效果预览图
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
*{
margin: 0;
padding: 0;
}
canvas{
display: block;
margin: 0 auto;
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas width="960" height="640"></canvas>
</body>
</html>
<script>
let can = document.querySelector('canvas');
let ctx = can.getContext('2d');
let img = new Image();
img.src = './images/3.jpeg';
img.onload = function(){
ctx.drawImage(img,0,0,can.width,can.height);
}
//鼠标进入canvas
can.onmouseenter = ()=>{
can.onmousemove=function(ev){
//清空
ctx.clearRect(0,0,can.width,can.height);
//绘画
ctx.drawImage(img,0,0,can.width,can.height);
//圆心
let x = ev.clientX - can.offsetLeft-1;
let y = ev.clientY - can.offsetTop-1;
// 只保留老图不重叠的部分其他清空
ctx.globalCompositeOperation = 'destination-out'
//画圆
ctx.beginPath();
ctx.arc(x,y,60,0,2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.globalCompositeOperation = 'destination-over';
//设置放大镜
ctx.drawImage(img,x*3-60,y*3-60,120,120,x-60,y-60,180,180)
}
}
can.onmouseleave = ()=>{
//清空
ctx.clearRect(0,0,can.width,can.height);
//绘画
ctx.drawImage(img,0,0,can.width,can.height);
}
</script>