0

I am trying to load an image from img directory, which is in src directory.

I have got a component called LocalImage in components directory, which is also in src.

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

class LocalImage extends React.Component {

  
  state = {
    image: null,
  };

  componentDidMount() {
    this.loadImage();
  }
  componentDidUpdate(oldProps) {
    if (oldProps.src !== this.props.src) {
      this.loadImage();
    }
  }
  componentWillUnmount() {
    this.image.removeEventListener('load', this.handleLoad);
  }
  loadImage() {
    // save to "this" to remove "load" handler on unmount
    this.image = new window.Image();
    this.image.src = this.props.src;
    this.image.addEventListener('load', this.handleLoad);
  }
  handleLoad = () => {
    // after setState react-konva will update canvas and redraw the layer
    // because "image" property is changed
    this.setState({
      image: this.image,
    });
    // if you keep same image object during source updates
    // you will have to update layer manually:
    // this.imageNode.getLayer().batchDraw();
  };
  render() {
    return (
      <Image
        x={this.props.x}
        y={this.props.y}
        image={this.state.image}
        ref={(node) => {
          this.imageNode = node;
        }}
      />
    );
  }
}

export default LocalImage ;

here is another components, which uses this one

import React from "react";
import { Stage, Layer, Rect, Circle, Image } from 'react-konva';
import LocalImage from "./LocalImage ";

const CanvasMod = function () {

    return (   
        <div className="editor_container">
            <Stage width={'600'} height={'600'}>
                <Layer>
                    <Rect width={50} height={50} fill="red" />
                    <Circle x={200} y={200} stroke="black" radius={50} />
                    //This is it
                    <LocalImage src="https://konvajs.org/assets/yoda.jpg"/>
                </Layer>
            </Stage>
            
        </div>
    )
}

export default CanvasMod;

If I put external address as src, such as https://konvajs.org/assets/yoda.jpg, everithing works. However if I put something such as ..img/img.png, it is not drawn

Alfred G
  • 1
  • 1

0 Answers0