簡體   English   中英

將圖像上傳到redux並在React-Konva中顯示

[英]Upload image to redux and show in React-Konva

我試圖將圖像上傳到Redux並以多種方式顯示在React-Konva中。 但這是行不通的。 在base64和blob中。 但是在正常情況下,例如使用組件的狀態來保存數據(base64),它是可以工作的。 我不知道為什么 在我的組件中,僅具有用於上傳的按鈕,而具有用於顯示圖像的React-Konva組件

這是來自redux中base64存儲的錯誤,並顯示給Image Tag

class UploadButton extends Component{
  constructor(props){
    ...
    this.handleUpload = this.handleUpload.bind(this);
  }

  handleUpload({target}){
    const reader = new FileReader();
    const file = target.files[0];
    reader.onloadend = () => {
      this.props.dispatch({
        type: 'UPLOAD_IMAGE',
        image: reader.result, 
      });
    };
    reader.readAsDataURL(file);
  }

  render(){
    return(
      <div>
        <input 
          value="Upload" 
          type="button" 
          onClick={ () => { this.uploadInput.click() } } 
        />
        <input 
          id="inputUpload"
          ref={ (ref) => { this.uploadInput = ref } }
          type="file" 
          style={ { display: 'none' } } 
          onChange = { (event) => { this.handleUpload(event) }}
        />
      </div>
    );

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { Stage, Layer, Image } from 'react-konva';

class ShowImage extends Component {
  constructor(props){
    super(props);
    this.props = props;

    this.state = {
      image : null,
    }
  }


  render(){
    return (
      <Stage
        width={ 500 }
        height={ 500 }
      >
        <Layer>
         <Image image={ this.props.image} ></Image>
        </Layer>
      </Stage>
    );
  }
}

const mapStateToProps = ( state ) => ({
  image : state.image,
});

export default connect(mapStateToProps)(ShowImage);

要在使用圖像react-konva你必須創建一個本地實例window.Image

class VaderImage extends React.Component {
  state = {
    image: new window.Image()
  };
  componentDidMount() {
    this.state.image.src = this.props.image;
    this.state.image.onload = () => {
      // need to update layer manually
      this.imageNode.getLayer().batchDraw();
    };
  }

  render() {
    return (
      <Image
        image={this.state.image}
        y={250}
        ref={node => {
          this.imageNode = node;
        }}
      />
    );
  }
}

https://konvajs.github.io/docs/react/Images.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM