9

Struggling a bit here. If I'm just filling or doing anything else to the canvas - no issue. I get the div without the external image. Tried local image file as well as URL... Thanks!

import React, { Component, PropTypes } from 'react';

export default class CanvasCreator extends Component {

componentDidMount() {
    this.updateCanvas();
}

updateCanvas() {
    const ctx = this.refs.canvas.getContext('2d');

    var imageObj1 = new Image();
    imageObj1.src = 'https://s-media-cache-ak0.pinimg.com/236x/d7/b3/cf/d7b3cfe04c2dc44400547ea6ef94ba35.jpg'
    ctx.drawImage(imageObj1,0,0);

}
render() {
    return (


        <canvas ref="canvas" width={300} height={300}> </canvas>

    );
 }
};
dualities
  • 99
  • 1
  • 1
  • 6

2 Answers2

18

You are missing the onload method. This will work for you:

   updateCanvas() {
    const ctx = this.refs.canvas.getContext('2d');

    var imageObj1 = new Image();
    imageObj1.src = 'https://s-media-cache-ak0.pinimg.com/236x/d7/b3/cf/d7b3cfe04c2dc44400547ea6ef94ba35.jpg'
 imageObj1.onload = function() {
        ctx.drawImage(imageObj1,0,0);
}

}
Lois Harris
  • 191
  • 1
  • 4
0

For me in order to work was also necessary to add the width and height!

Example:

imageObj1.onload = function() {
    ctx.drawImage(imageObj1, 0, 0, 500, 500)
}
some-user
  • 3,888
  • 5
  • 19
  • 43
Rita Moreira
  • 101
  • 1
  • 5