vue3+jointjs demo

发布时间 2023-04-24 18:49:44作者: longlinji
下面是使用Vue3和JointJS添加元素的示例代码:

1. 安装JointJS

```terminal
npm install jointjs --save
```

2. 创建JointJS图形

```javascript
import { ref, onMounted } from 'vue';
import * as joint from 'jointjs';

export default {
  setup() {
    const graphContainer = ref(null);
    let paper = null;
    let rect = null;

    onMounted(() => {
      // 创建JointJS图形
      paper = new joint.dia.Paper({
        el: graphContainer.value,
        width: 800,
        height: 600,
        model: new joint.dia.Graph(),
        gridSize: 1
      });

      // 创建矩形元素
      rect = new joint.shapes.standard.Rectangle();
      rect.position(100, 100);
      rect.resize(100, 50);
      rect.attr({
        body: {
          fill: 'blue'
        },
        label: {
          text: 'My Rectangle',
          fill: 'white'
        }
      });

      // 将矩形元素添加到图形中
      const graph = paper.model;
      graph.addCells([rect]);

      // 支持拖动
      paper.on('blank:pointerdown', function (evt, x, y) {
        $('body').css('cursor', 'move');
        paper.translate(-x, -y);
      });

      paper.on('cell:pointerdown', function (cellView, evt) {
        $('body').css('cursor', 'move');
      });

      paper.on('cell:pointerup', function (cellView, evt, x, y) {
        $('body').css('cursor', 'default');
      });

      paper.on('blank:pointerup', function (evt, x, y) {
        $('body').css('cursor', 'default');
      });
    });

    return {
      graphContainer
    };
  }
};
```

上面的代码中,我们先创建了JointJS图形,然后创建了一个矩形元素,并将其添加到图形中。最后,我们实现了支持拖动的功能。

使用上面的代码,你可以在Vue3中快速、方便地添加元素。