Fabricjs,选择手柄显示但在与其他形状一起选择之前不可点击

Fabricjs, selection handles shown but not clickable before selected together with other shapes

我正在尝试开发一个 vue.js 组件来使用 fabricjs 绘制形状。 绘制矩形后,它是可选择的,但不能使用选择手柄调整大小或旋转,这不是我所期望的。我认为它与 vue.js 3 有关,因为一切都适用于 vue.js 2.

this demo at JSFiddle 中,角手柄不适用于矩形,直到您选择了矩形和其他形状。


<div id="app">
<canvas ref="c"></canvas>
<div>
<button type="button" @click="add('red')">
Add
</button>
Select the blue rectangle. The corner handles are visible but not working.
Now, click "add“, then select both rectangles. Then just select any single item, now the corner handles are working.
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0/vue.global.js"></script>


var vm = Vue.createApp({
  data: () => ({
    canvas: null
  }),
  mounted: function() {
    var c = this.$refs.c
    this.canvas = new fabric.Canvas(c, {
      width: c.clientWidth,
      height: c.clientHeight
    });
    this.add('blue')
  },
  methods: {
    add(color) {
      this.canvas.add(new fabric.Rect({
        top: 20,
        left: 20,
        width: 40,
        height: 40,
        fill: color
      }))
    }
  }
}).mount('#app');

// Select the blue rectangle. The corner handles are visible but not working.
// Now, click "add", then select both rectangles. 
// Then just select any single item, now the corner handles are working. 

如何在坚持使用 vue.js 3 的同时解决这个问题?

Fabricjs 不喜欢将 canvas 转换为代理。解决它的一种方法是使用全局变量而不是使用数据。您也可以只从 data() 声明中删除 canvas,这将使它在整个模板和代码中仍然可以访问,但不会使其响应。

示例:

var vm = Vue.createApp({
  mounted: function() {
    var c = this.$refs.c
    this.canvas = new fabric.Canvas(c, {
      width: c.clientWidth,
      height: c.clientHeight
    });
    this.add('blue')
  },
  methods: {
    add(color) {
      this.canvas.add(new fabric.Rect({
        top: 20,
        left: 20,
        width: 40,
        height: 40,
        fill: color
      }))
    }
  }
}).mount('#app');
<div id="app">
  <canvas ref="c"></canvas>
  <div>
    <button type="button" @click="add('red')">
      Add
    </button>
    Select the blue rectangle. The corner handles are visible but not working.
    Now, click "add“, then select both rectangles. Then just select any single item, now the corner handles are working.
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0/vue.global.prod.js"></script>

您可以使用 toRaw()。该函数可以将代理对象更改为普通对象。

add(color) {
  toRaw(this.canvas).add(new fabric.Rect({
    top: 20,
    left: 20,
    width: 40,
    height: 40,
    fill: color
  }))
}