Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React -- Canvas Won't Draw Image

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>

    );
 }
};
like image 740
dualities Avatar asked Oct 07 '16 02:10

dualities


People also ask

How do I create a canvas image in Reactjs?

Firstly, use image onload event to wait and start drawing after the <img> element has finished loading. Then use the drawImage(image,x,y) method to draw our image starting at the top left corner of the canvas. The drawImage takes 3 parameters. This will draw the image on the canvas.

Does canvas work in react?

Giving Canvas a Home: js component, although the canvas element can be housed in any standard React. js component. The application will render the canvas element, and will draw a heart at the coordinates specified by an onClick() event listener.

What is react Konva?

React Konva is a JavaScript library for drawing complex canvas graphics using React. It provides declarative and reactive bindings to the Konva Framework.


1 Answers

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

}
like image 64
Lois Harris Avatar answered Oct 03 '22 03:10

Lois Harris