将图像上传到 redux 并在 React-Konva 中显示

Upload image to redux and show in React-Konva

我尝试过将图像上传到 Redux 并以多种方式在 React-Konva 中显示。但这是行不通的。在 base64 和 blob 中。但是在正常情况下,比如使用组件的状态来保存数据(base64),它是有效的。我不知道为什么。 在我的组件中只有用于上传的按钮和用于显示图像的 React-Konva 组件

this is error from base64 store in redux and show to 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