Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在React中的画布元素上加载图像_Reactjs_Canvas - Fatal编程技术网

Reactjs 在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

我试图在React中将图像加载到画布上。这是我用来做这件事的代码

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;