2017-10-07 51 views
0

我正在嘗試創建一個用戶界面來與fabricjs畫布進行交互。左邊是一個組件,顯示可以添加到畫布的項目庫。中間是fabricjs畫布,右側是一個組件,列出畫布上所有添加的項目(類似於photoshops圖層面板)。反應:與來自另一個組件的fabric.js畫布實例進行交互

我想知道如何在左邊的組件(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> 

如何從<Item/>中訪問畫布實例?

在情況下,它相關的答案,同時,我還需要在右邊(<LayersPanel/>)的組件來顯示什麼是添加到畫布。

感謝

回答

0

我設法用下面的做到這一點...

創建畫布...

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

從任何地方(只要把它撿起來,因爲它已經加載當然)...

canvas = document.getElementById("c").fabric; 
相關問題