vue3+jointjs 使用模板添加元素

<template>
  <div>
    <div ref="canvasContainer" style="height: 500px;"></div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { dia } from 'jointjs';

export default {
  setup() {
    const canvasContainer = ref(null);
    
    onMounted(() => {
      // create a new paper instance in the canvas container
      const paper = new dia.Paper({
        el: canvasContainer.value,
        width: '100%',
        height: '100%',
        model: new dia.Graph(),
      });

      // define the shape template
      const template = dia.Element.define(
        'myShape', // name of the shape
        {
          markup: [
            {
              tagName: 'rect',
              selector: 'body',
            },
          ],
          attrs: {
            body: {
              fill: 'white',
              stroke: 'black',
              strokeWidth: 2,
              width: 100,
              height: 50,
            },
          },
        },
        {
          // define a view for the shape
          view: dia.ElementView.extend({
            initialize() {
              dia.ElementView.prototype.initialize.apply(this, arguments);
            },
          }),
        }
      );

      // add the template to the stencil
      const stencil = new dia.Stencil({
        paper,
        width: 180,
        height: '100%',
        groups: {
          basic: {
            label: 'Basic Shapes',
            index: 1,
          },
        },
        dropAnimation: true,
        groupsToggleButtons: true,
        search: {
          '*': ['type', 'attrs/body/filter']
        }
      });
      stencil.render().$el.appendTo('#stencil-container');
      stencil.load([{ shape: template, attrs: { label: { text: 'My Shape' } } }]);

      // add an instance of the shape to the canvas
      paper.model.addCell(
        new template({
          position: { x: 100, y: 100 },
          size: { width: 100, height: 50 },
        })
      );
    });

    return {
      canvasContainer,
    };
  },
};
</script>

 

posted on 2023-04-25 09:40  longlinji  阅读(127)  评论(0编辑  收藏  举报