I'm trying to load an image onto a canvas in React. This is the code I am using to do this.
import React, { Component } from 'react';
class Image extends Component {
constructor(props) {
super(props);
this.canvasRef = React.createRef();
}
componentDidMount() {
const canvas = this.canvasRef.current;
const context = canvas.getContext('2d');
const image = new Image();
image.onload = () => {
context.drawImage(image, 0, 0)
}
image.src = 'http://lorempixel.com/400/200/sports/1/';
};
render() {
return(
<div>
<canvas ref={this.canvasRef} width={2400} height={1200}/>
</div>
);
}
}
export default Image
Yet I am getting blank page whenever I load the image. I've followed the answers from How to load Image on canvas in React?, draw image on canvas, and How could we load a local image on a canvas?. None of these steps seem to get the image on the canvas. The only time I've been successful is following the steps in this blog https://blog.cloudboost.io/using-html5-canvas-with-react-ff7d93f5dc76 but it seems to me that loading the image twice shouldn't be necessary as the image should be loaded in the onLoad
method. I've also tried moving the image.src
assignment to after the onLoad
method and before as some other people have suggested in the referenced SO questions yet it is not working. There are no issues in the console either.
This class is being loaded in an App.js
file that is then run using yarn start
import React from 'react';
import Image from './Image';
function App() {
return (
<div className="App">
<Image/>
</div>
);
}
export default App;