vue结合 Fabric.js 实现鼠标拖动画布、滚轮缩放画布的功能

1. 效果展示

  1. vue 结合 fabric.js 用canvas画布画底图
  2. 实现鼠标拖动画布底图
  3. 实现鼠标滚动对画布底图进行放大缩小
    在这里插入图片描述

2. 引入 fabric.js

2.1 npm 安装

npm install fabric --save

2.2 main.js 导入

import { fabric } from 'fabric'
Vue.use(fabric);

3.3 vue 页面实现

<template>
  <div>
    <div class="manager_detail">
      <canvas id="canvas" width="1720" height="1050"></canvas>
    </div>
  </div>
</template>
<script>
export default {
  components: {
  },
  watch: {},
  data() {
    return {
      panning: false
    };
  },
  methods: {
    initCanvas() {
      // 1. 实例化canvas 画布
      var canvas = new fabric.Canvas("canvas");
      // 2. 设置背景图片作为底图(这里导入图片使用require,不要 使用 '../../' 方式)
      // canvas.width / 4764  (4764 是我底图图片宽度)
      // canvas.height / 3367 (3367 是我底图图片宽度)
      canvas.setBackgroundImage(
        require("../../assets/images/map.png"),
        canvas.renderAll.bind(canvas),
        {
          scaleX: canvas.width / 4764,
          scaleY: canvas.height / 3367
        }
      );

      //鼠标按下事件
      canvas.on("mouse:down", function(e) {
        this.panning = true;
        canvas.selection = false;
      });
      //鼠标抬起事件
      canvas.on("mouse:up", function(e) {
        this.panning = false;
        canvas.selection = true;
      });
      // 移动画布事件
      canvas.on("mouse:move", function(e) {
        if (this.panning && e && e.e) {
          var delta = new fabric.Point(e.e.movementX, e.e.movementY);
          canvas.relativePan(delta);
        }
      });
      // 鼠标滚动放大缩小画布
      // 
      if (document.getElementById("canvas")) {
        // IE9, Chrome, Safari, Opera
        document.addEventListener("mousewheel", function(e) {
          if (e.target.className == "upper-canvas ") {
            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);
          }
        });
      }
    }
  },
  created() {
  },
  mounted() {
    this.initCanvas();
  }
};
</script>
<style scoped>
.manager_detail {
  width: 100%;
  height: calc(100vh - 112px);
  overflow: hidden;
}
</style>

3.3 底图图片大小
在这里插入图片描述

3. 采坑

3.1 图片使用require,不要 使用 '../../' 方式,否则图片加载不进去

3.2 监听鼠标滚动实现画布底图放大缩小问题

关于鼠标滚动实现元素放大缩小问题,下面这种方式也可以实现,但是vue项目需要引入jquery,本身不合理的,所以。可以采用我上面那种方式(用原生的 addEventListener 事件注册到根元素上 document 通过 e.target.className 来判断事件源,然后通过 fabriczoom 的属性来进行放大缩小功能 )

在这里插入图片描述
在这里插入图片描述

发布了113 篇原创文章 · 获赞 99 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/qq_36410795/article/details/104424897