鼠标移动 图片局部放大 —利用到canvas
(第一篇文章解决的思路是—准备一张大图去实现的----类似仿京东放大镜的效果)
思路 : 根据鼠标的位置去画----画的图位100100----用200200去放大显示
用到的文档 https://www.w3school.com.cn/html5/canvas_drawimage.asp
效果图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#box{
position:relative;
width:478px;
height:720px;
/* border:1px solid red; */
margin:0 auto;
}
#container{
position:absolute;
top:0px;
width:200px;
height:200px;
border:1px solid blue;
}
</style>
</head>
<body>
<div id="box">
<img src="./up.jpg" alt="" id="img1" />
<div id="container">
<canvas id="canvas" width="200" height="200"> </canvas>
</div>
</div>
<script>
window.onload = function () {
var box=document.getElementById('box')
var img1=document.getElementById('img1')
var cont=document.getElementById('container')
var canvas=document.getElementById('canvas')
var ctx=canvas.getContext("2d");
box.addEventListener('mousemove',function(event){
var cx=event.clientX-box.offsetLeft-cont.offsetWidth/2
var cy=event.clientY-box.offsetTop-cont.offsetHeight/2
// console.log(cx,cy);
// ---内框最大的移动距离
var max=box.offsetWidth-cont.offsetWidth
var may=box.offsetHeight-cont.offsetHeight
if(cx<=0){
cx=0
}
if(cx>=max){
cx=max
}
if(cy<=0){
cy=0
}
if(cy>=may){
cy=may
}
cont.style.top=cy+'px'
cont.style.left=cx+'px'
console.log(cx,cy);
var dx
var dy
if(cx<=0){
dx=0
}else{
dx=cx+50
}
if(cy<=0){
dy=0
}else{
dy=cy+50
}
ctx.drawImage(img1,dx,dy,100,100,0,0,200,200);
})
}
</script>
</body>
</html>