0

I'm trying to load/draw a local image on canvas but it's not showing up.

        render(state) {
                const context = state.context;

                const image=new Image();
                image.onload=function(){
                    context.drawImage(image, this.position.x, this.poxition.y);
                };
                image.onerror=function(){alert("image load failed")};
                image.src="./image.png"
        }

and this is from the main component I'm importing the above into:

componentDidMount() {
        const context = this.refs.canvas.getContext('2d');
        this.setState({ context: context });
}
omcc
  • 25
  • 1
  • 5

1 Answers1

0

Use require to load images and don't add listeners(like onload, onError etc) in render, do it in componentDidMount.

Working demo is here

Code Snippet

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  state = {};
  ref = React.createRef(null);
  componentDidMount() {
    const context = this.ref.current.getContext("2d");
    const image = new Image();
    image.onload = function(res) {
      console.log("res", res);
      context.drawImage(image, 0, 0);
    };
    image.onerror = function(err) {
      console.log("err", err);
    };
    image.src = require("./tree.jpeg");
  }
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <canvas ref={this.ref} />
      </div>
    );
  }
}

gdh
  • 13,114
  • 2
  • 16
  • 28