当前位置: > > > Fabric.js - 解决IE下鼠标拖动画布功能失效问题(无法取到movementX、movementY)

Fabric.js - 解决IE下鼠标拖动画布功能失效问题(无法取到movementX、movementY)

1,问题描述

    在之前的文章中我介绍到了何如实现鼠标拖动画布的功能(点击查看)。但发现这个功能在火狐、Chrome 浏览器下是正常的,而在 IE 下就无法使用(不能移动画布)。

2,问题原因

    问题在于下面的“mouse:move”事件响应代码,IE 下获取不到 e.e.movementX e.e.movementY 的值(返回都是 undefined),从而造成画布无法移动。
//鼠标移动
canvas.on('mouse:move', function (e) {
    if (panning && e && e.e) {
        var delta = new fabric.Point(e.e.movementX, e.e.movementY);
        canvas.relativePan(delta);
    }
});

3,解决办法

    这里对“mouse:move”事件响应代码稍作修改:在取不到 movementX movementY 的情况下,通过计算两次鼠标事件的 screenX screenY 的差值得到移动距离,从而支持 IE 浏览器。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
    canvas {
        border: 1px dashed black;
    }
</style>
<script src="fabric.js"></script>
<script src="jquery-3.1.1.js"></script>
<script src="jquery.mousewheel.js"></script>
<script>
  var canvas;

  //是否拖动
  var panning = false;

  //前一个鼠标移动事件
  var previousEvent;

  window.onload = function() {
    canvas = new fabric.Canvas('canvas');

    var rect1 = new fabric.Rect({top: 50, left: 50, width: 70, height: 70, fill: 'red'});
    canvas.add(rect1);
    var rect2 = new fabric.Rect({top: 50, left: 150, width: 70, height: 70, fill: 'red'});
    canvas.add(rect2);
    var rect3 = new fabric.Rect({top: 50, left: 250, width: 70, height: 70, fill: 'red'});
    canvas.add(rect3);

    //鼠标按下
    canvas.on('mouse:down', function (e) {
        //按住alt键才可拖动画布
        //if(e.e.altKey) {
          panning = true;
          canvas.selection = false;
        //}
    });

    //鼠标抬起
    canvas.on('mouse:up', function (e) {
        panning = false;
        canvas.selection = true;
    });

    //鼠标移动
    canvas.on('mouse:move', function (e) {
      if (panning && e && e.e) {
         var x = e.e.movementX;
         var y = e.e.movementY;
         if(!x) {
             x = e.e.screenX - previousEvent.e.screenX;
             y = e.e.screenY - previousEvent.e.screenY;
         }
         var delta = new fabric.Point(x, y);
         canvas.relativePan(delta);
      }
      previousEvent = e;
    });

    //鼠标滚轮监听
    $(".upper-canvas").mousewheel(function(event) {
        var zoom = (event.deltaY > 0 ? 0.1 : -0.1) + canvas.getZoom();
        zoom = Math.max(0.1,zoom); //最小为原来的1/10
        zoom = Math.min(3,zoom); //最大是原来的3倍
        var zoomPoint = new fabric.Point(event.pageX, event.pageY);
        canvas.zoomToPoint(zoomPoint, zoom);
    });
  }
</script>
</head>
<body>
    <canvas id="canvas" width="600" height="160"></canvas>
</body>
</html>
评论0