如何在React中的画布上加载图像? [英] How to load Image on canvas in React?
本文介绍了如何在React中的画布上加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在React中将图像上传到画布的整个宽度/高度?例如:
How to upload Image to the full width/height of the canvas in React? for example:
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>
将不胜感激。
推荐答案
您可以尝试以下类似方法
You can try something like this
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);
};
}
这篇关于如何在React中的画布上加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文