vue結合 Fabric.js 實現鼠標拖動畫布、滾輪縮放畫布的功能

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,不要 使用 '../../' 方式,否則圖片加載不進去

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章