【问题标题】:React: Interact with fabric.js canvas instance from another componentReact:与另一个组件中的 fabric.js 画布实例交互
【发布时间】:2018-03-19 02:29:00
【问题描述】:

我正在尝试创建一个 UI 以与 fabricjs 画布进行交互。左侧是一个组件,显示可以添加到画布的项目库。中间是fabricjs画布,右边是一个组件,列出了画布上所有添加的项目(类似于photoshops图层面板)。

我想知道如何在左侧的组件 (ItemsList.js) 中有一个 onClick 事件,访问在其父组件中声明的 fabricjs 画布实例。

这是主要组件...

MainComponent.js

import React, { Component } from 'react';
import { createContainer } from 'meteor/react-meteor-data';

import ItemsList from './ItemsList.js';
import LayersPanel from './LayersPanel.js';

import {fabric} from 'fabric';

class Designer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      canvasWidth: ''
    };
  }

  updateCanvasDimensions() {
    this.setState({
      canvasWidth: this.refs.canvas_wrapper.offsetWidth
    });
    canvas.setHeight(this.state.canvasWidth);
    canvas.setWidth(this.state.canvasWidth);
  }

  componentDidMount() {
    canvas = new fabric.Canvas('c', {
      width: this.refs.canvas_wrapper.offsetWidth,
      height: this.refs.canvas_wrapper.offsetWidth
    });
    this.updateCanvasDimensions(canvas);
    window.addEventListener("resize", this.updateCanvasDimensions.bind(this));
    canvas.renderAll();
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updateCanvasDimensions.bind(this));
  }

  render() {
    return (
      <div>

          <div>
            <ItemsList />
          </div>

          <div className="canvas-wrapper" ref="canvas_wrapper">
            <canvas ref="c" id = "c"></canvas>
          </div>

          <div>
            <LayersPanel />
          </div>

      </div>
    );
  }
}

export default createContainer(({ params }) => {

  return {
  };

}, Designer);

在 ItemsList.js 中的某处,对于列表中的每个项目,都有一个用于将项目的图像添加到画布的按钮。

...
<Button onClick={() => {

    //Need to get the canvas instance here so 
    //that I can add this particular item's image to the canvas like this...

    canvas.add(rowData.image);

}}>Add Item</Button>
...

在为 ItemsList 组件中的特定项目单击此按钮后,我希望将单击的项目的图像添加到树上组件中声明的画布中。比如……

<MainComponent> <-- This is where I declare the fabric canvas.
  <ItemsList>
     <Item/>  <-- This is where the button is clicked.
  </ItemsList>
</MainComponent>

如何从&lt;Item/&gt; 中访问画布实例?

如果它与答案相关,同时我还需要右侧的组件(&lt;LayersPanel/&gt;)来显示添加到画布的内容。

谢谢

【问题讨论】:

    标签: reactjs meteor fabricjs


    【解决方案1】:

    我已经设法通过以下方式做到这一点......

    创建画布...

    <canvas ref="c" id = "c"></canvas>
    

    从任何地方拿起它(当然,只要它已经加载)......

     canvas = document.getElementById("c").fabric;
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2018-02-20
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2011-09-21
      • 2013-08-17
      相关资源
      最近更新 更多