1. 效果展示

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

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);
        }
      });
      // 鼠标滚动画布放大缩小
      canvas.on("mouse:wheel", function(e) {
        var zoom = (event.deltaY > 0 ? -0.1 : 0.1) + _that.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);
        _that.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,不要 使用 '../../' 方式,否则图片加载不进去

Logo

前往低代码交流专区

更多推荐