How to load Image on canvas in React?

12,410

You can try something like this

componentDidMount() {
  const context = this.canvasA.getContext('2d');

  const image = new Image();
  image.src = "whereever-you-image-url-live.jpg";
  image.onload = () => {
    context.drawImage(image, 0, 0, this.canvasA.width, this.canvasA.height);
  };
}
Share:
12,410

Related videos on Youtube

vladimir.nam
Author by

vladimir.nam

Hi! My name is Vladimir. I'm Front-end developer with 3+ years of experience in Angular/React/ReactNative technologies.

Updated on July 13, 2022

Comments

  • vladimir.nam
    vladimir.nam almost 2 years

    How to upload Image to the full width/height of the canvas in React? for example:

    class PlanPage extends Component {
      constructor(props) {
        super(props);
      }
    
      componentWillMount() {
        this.setState({
          canvasA: {
            canvasWidth: 800,
            canvasHeight: 600
          }
        })
      }
    
      componentDidMount() {
        this.props.getDataMap(); //return object which has the fields e.g. id,... and field URL which specifies where image is  
        const { canvasWidth, canvasHeight } = this.state.canvasA;
        this.canvasA.width = canvasWidth;
        this.canvasA.height = canvasHeight;
      }
    ......
    <canvas
      ref={canvasA => this.canvasA = canvasA} /> //canvas
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    will appreciated any help.

  • Max Carroll
    Max Carroll almost 4 years
    30 minutes to discover I had used onLoad instead of onload . Just thought I would share that because if you're here you might wonder if there's something magical about react that is preventing your canvas from working, when in actual fact perhaps you made a silly mistake like me
  • Nick Wyman
    Nick Wyman almost 4 years
    Yeah, you have to aware of what type of object you are using. If you are using a React image object, it would be onLoad. But if it is a regular HTML img element, it is onload. In this case, since it just in a canvas, its the regular HTML image element.
  • matepal297
    matepal297 over 3 years
    first set image.onload, then image.src