如何在 React 中将图像加载到画布上?

2024-06-19

如何在 React 中将图像上传到画布的整个宽度/高度?例如:

class PlanPage extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.setState({
      canvasA: {
        canvasWidth: 800,
        canvasHeight: 600
      }
    })
  }

  componentDidMount() {
    this.props.getDataMap(); //return object which has the fields e.g. id,... and field URL which specifies where image is  
    const { canvasWidth, canvasHeight } = this.state.canvasA;
    this.canvasA.width = canvasWidth;
    this.canvasA.height = canvasHeight;
  }
......
<canvas
  ref={canvasA => this.canvasA = canvasA} /> //canvas
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

将不胜感激任何帮助。


你可以尝试这样的事情

componentDidMount() {
  const context = this.canvasA.getContext('2d');

  const image = new Image();
  image.src = "whereever-you-image-url-live.jpg";
  image.onload = () => {
    context.drawImage(image, 0, 0, this.canvasA.width, this.canvasA.height);
  };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React 中将图像加载到画布上? 的相关文章

随机推荐