【问题标题】:Load an Image on a Canvas element in React在 React 中的 Canvas 元素上加载图像
【发布时间】:2019-10-24 16:34:19
【问题描述】:

我正在尝试将图像加载到 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

然而,每当我加载图像时,我都会得到空白页。我已经关注了How to load Image on canvas in React?draw image on canvasHow could we load a local image on a canvas? 的答案。这些步骤似乎都没有在画布上获得图像。我唯一一次成功是按照此博客https://blog.cloudboost.io/using-html5-canvas-with-react-ff7d93f5dc76 中的步骤进行操作,但在我看来,两次加载图像应该是不必要的,因为图像应该在onLoad 方法中加载。我还尝试将 image.src 分配移到 onLoad 方法之后和之前,正如其他人在引用的 SO 问题中所建议的那样,但它不起作用。控制台也没有问题。

此类正在加载到 App.js 文件中,然后使用 yarn start 运行该文件

import React from 'react';
import Image from './Image';

function App() {
  return (
    <div className="App">
        <Image/>
    </div>
  );
}

export default App;

【问题讨论】:

    标签: reactjs canvas


    【解决方案1】:

    将图片保存在目录的public文件夹中

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2016-09-18
      相关资源
      最近更新 更多