canvas+javascript实现淘宝商品放大镜效果
程序员文章站
2022-07-05 15:19:57
canvas 绘制图片是根据原始图片的尺寸进行绘制,而不是根据利用属性或样式放大缩小后的图片,所以要乘以原始图片与现在图片的比例。 ......
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>jquery之家</title> <style type="text/css"> *{margin:0;padding:0;} body{font-size: 14px;} canvas{ display:none; background-color: #ffff91; } #square{ width:80px; height: 80px; background-color: rgba(117,240,255,0.5); position:absolute; z-index: 999; cursor:crosshair; display:none; } </style> <script> onload=function(){ var canvas=document.getelementbyid("canvas");//获取画布 var ctx=canvas.getcontext("2d");//获取画笔 var img=document.getelementsbytagname("img")[0];//获取图片 var square=document.getelementbyid("square");//获取选择框 var squaredata={};//存选择框信息 var imgposition=img.getboundingclientrect();//获取图片的位置 var p=img.naturalwidth/img.width;//原始图片与缩小后图片的比例 // var even; //鼠标移入 img.onmouseove=function(e){ var even=e||event;//兼容火狐浏览器 var x=even.clientx, y=even.clienty; createsquare(x,y); }; window.onmousemove=function(e){ var even=e||event; var x=even.clientx; var y=even.clienty; //使选择框限制在图片内部 if(x>=img.offsetleft&&x<=img.offsetleft+img.width&&y>=img.offsettop&&y<=img.offsettop+img.height){ createsquare(x,y); }else{ hidesquare(); hidecanvas(); } }; function createsquare(x,y){ x=x-40<img.offsetleft?img.offsetleft:x-40; y=y-40<img.offsettop?img.offsettop:y-40; x=x+80<imgposition.right?x:imgposition.right-80; y=y+80<imgposition.bottom?y:imgposition.bottom-80; //将选择框左上角的位置存到squaredata squaredata.left=x; squaredata.top=y; movesquare(x,y); } function movesquare(x,y){ //设置选择框偏移位置 square.style.left=x+"px"; square.style.top=y+"px"; showcanvas(); showsquare(); draw(); } function showcanvas(){ canvas.style.display="inline"; } function hidecanvas(){ canvas.style.display="none"; } function showsquare(){ square.style.display="inline"; } function hidesquare(){ square.style.display="none"; } //将放大后的图片画到canvas中 function draw(){ console.log(squaredata.left-imgposition.left); ctx.drawimage(img,(squaredata.left-imgposition.left)*p,p*(squaredata.top-imgposition.top),p*80,p*80,0,0,canvas.width,canvas.height); } } </script> </head> <body> <img src="img/n7etzfo.jpg" alt="" width="300px"> <canvas id="canvas" width="300px" height="225px"></canvas> <div id="square"></div> </body> </html>
canvas 绘制图片是根据原始图片的尺寸进行绘制,而不是根据利用属性或样式放大缩小后的图片,所以要乘以原始图片与现在图片的比例。