React -- Canvas Won't Draw Image
Asked Answered
T

2

11

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>

    );
 }
};
Thayne answered 7/10, 2016 at 2:45 Comment(0)
A
19

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);
}

}
Andri answered 21/12, 2016 at 15:6 Comment(0)
F
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)
}
Finegan answered 28/9, 2022 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.