1949啦网--小小 痛苦,是因为能力和欲望不匹配造成的

canvas实现放大镜效果实现HTML5

下面来实现一个放大镜的效果,鼠标按下并移动时,显示当前图片区域的放大效果,抬起后效果消失。放大镜效果主要使用离屏canvas的技术,离屏canvas放置的是图片的放大版,而普通canvas则放置图片的正常版

<!DOCTYPE html>      <html>      	<head>      		<meta charset="UTF-8">      		<title></title>      </head>  <body>  <canvas id="drawing" style="border:1px solid black">      <p>The canvas element is not supported!</p>  </canvas>  <canvas id="drawingOff" style="display:none">      <p>The canvas element is not supported!</p>  </canvas>  </body>  <script type="text/javascript">  if(drawing.getContext){    var cxt = drawing.getContext('2d');    var cxtOff = drawingOff.getContext('2d');    var W,H;     var scale = 1.5;     var img = new Image();    img.src="https://www.qiquanji.com/data/img/dmj/201905051557020391812974.jpg";    img.onload = function(){      W = img.width;      H = img.height;      drawing.width = W/scale;      drawing.height = H/scale;      drawingOff.width = W;      drawingOff.height = H;      cxt.drawImage(img,0,0,W/scale,H/scale);      cxtOff.drawImage(img,0,0);      drawing.onmousedown = function(e){        e = e || event;        var x0 = this.offsetLeft;        var y0 = this.offsetTop;         drawMagnifier(e);        drawing.onmousemove = function(e){          drawMagnifier(e);        }        document.onmouseup = function(e){          cxt.clearRect(0,0,W/scale,H/scale);          cxt.drawImage(img,0,0,W/scale,H/scale);          drawing.onmousemove = null;        }                function drawMagnifier(e){          cxt.clearRect(0,0,W/scale,H/scale);          cxt.drawImage(img,0,0,W/scale,H/scale);          var x = (e.clientX-x0);          var y = (e.clientY-y0);                  var r = 40;          var dx = x - r;          var dy = y - r;          var sx = x*scale - r;          var sy = y*scale - r;          cxt.save();          cxt.beginPath();          cxt.arc(x,y,r,0,Math.PI*2);          cxt.lineWidth = 4;          cxt.strokeStyle = '#069';          cxt.stroke();          cxt.clip();          cxt.drawImage(drawingOff,sx,sy,2*r,2*r,dx,dy,2*r,2*r);          cxt.restore();                 }      }    }   }  </script>  </html>

原文链接:https://www.qiquanji.com/post/7033.html

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

微信扫码关注

更新实时通知

作者:xialibing 分类:网页教程 浏览: