canvas实现放大镜效果实现HTML5

时间:5年前   阅读:4949

下面来实现一个放大镜的效果,鼠标按下并移动时,显示当前图片区域的放大效果,抬起后效果消失。放大镜效果主要使用离屏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,我们将及时处理。

微信扫码关注

更新实时通知

上一篇:javascript 6个常见错误

下一篇:50ETF期权怎样正确的看待买卖双方?

网友评论

请先 登录 再评论,若不是会员请先 注册