Reactjs 在React中的画布元素上加载图像
我试图在React中将图像加载到画布上。这是我用来做这件事的代码Reactjs 在React中的画布元素上加载图像,reactjs,canvas,Reactjs,Canvas,我试图在React中将图像加载到画布上。这是我用来做这件事的代码 import React, { Component } from 'react'; class Image extends Component { constructor(props) { super(props); this.canvasRef = React.createRef(); } componentDidMount() { const canvas = this.canvasRe
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
将图像保存在目录的public文件夹中将图像保存在目录的public文件夹中
import React from 'react';
import Image from './Image';
function App() {
return (
<div className="App">
<Image/>
</div>
);
}
export default App;