Fabric.js - 在渲染组之前等到loadedSVGFromString完成

时间:2017-11-09 09:33:58

标签: javascript fabricjs

我正在与Fabric.js合作创建一个交互式画布。当用户点击按钮时,我调用了我的diagram.js文件中的addNewItem函数。单击此按钮后,我想将新组添加到画布的中心。我遇到的问题是,我要添加到组中的两个元素之一是我通过Fabric自己的loadSVGFromString方法加载的SVG。这需要时间来完成,这意味着在下面的示例中,未在Promise中定义group

diagram.js(仅显示相关代码)

addNewItem = (e, item) => {
  e.preventDefault();

  drawPlayer(item.svg, this.state.playerIconColor, borderColor, item.sizes[this.state.iconSize].height, item.sizes[this.state.iconSize].width, 'LM')
  .then((newItem) => {
    newItem.hasControls = false;
    canvas
      .add(newItem)
      .centerObject(newItem)
      .setActiveObject(newItem)
      .renderAll();
    newItem.setCoords();
  })
  .catch((notCreated) => {
    alert(notCreated);
  });
}

drawPlayer.js

import { fabric } from 'fabric';

const drawPlayer = (icon, iconFill, borderColor, height, width, label) => {
  // Create empty group
  let group;

  fabric.loadSVGFromString(icon, (objects, options) => {
    const canvasItem = fabric.util.groupSVGElements(objects, options);
    canvasItem.hasControls = false;
    canvasItem.setFill(iconFill);
    canvasItem.set({ borderColor });
    canvasItem.scaleToHeight(height);
    canvasItem.scaleToWidth(width);

    const playerText = new fabric.Text(label, {
      fontSize: 10,
      originX: 'center',
      originY: 'center',
    });

    group = new fabric.Group([canvasItem, playerText], { left: 200, top: 200 });
  });

  return new Promise((resolve, reject) => {
    if (group.length > 0) {
      resolve(group);
    } else {
      reject('Not created');
    }
  });
};

export default drawPlayer;

1 个答案:

答案 0 :(得分:1)

您可以在loadSVGFromString执行后尝试解析/拒绝承诺。

import { fabric } from 'fabric';

const drawPlayer = (icon, iconFill, borderColor, height, width, label) => {
  // Create empty group
  let group;
  let groupResolve;
  let groupReject;

  fabric.loadSVGFromString(icon, (objects, options) => {
    const canvasItem = fabric.util.groupSVGElements(objects, options);
    canvasItem.hasControls = false;
    canvasItem.setFill(iconFill);
    canvasItem.set({ borderColor });
    canvasItem.scaleToHeight(height);
    canvasItem.scaleToWidth(width);

    const playerText = new fabric.Text(label, {
      fontSize: 10,
      originX: 'center',
      originY: 'center',
    });

    group = new fabric.Group([canvasItem, playerText], { left: 200, top: 200 });
    if (group.length > 0) {
      groupResolve(group);
    } else {
      groupReject('Not created');
    }
  });

  return new Promise((resolve, reject) => {
    groupResolve = resolve;
    groupReject = reject;
  });
};

export default drawPlayer;