<!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{ 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 绘制图片是根据原始图片的尺寸进行绘制,而不是根据利用属性或样式放大缩小后的图片,所以要乘以原始图片与现在图片的比例。