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 繪製圖片是根據原始圖片的尺寸進行繪製,而不是根據利用屬性或樣式放大縮小後的圖片,所以要乘以原始圖片與現在圖片的比例。