我正在尝试在画布上加载/绘制本地图像,但是没有显示出来。
render(state) {
const context = state.context;
const image=new Image();
image.onload=function(){
context.drawImage(image, this.position.x, this.poxition.y);
};
image.onerror=function(){alert("image load failed")};
image.src="./image.png"
}
这是从主要组件中导入的内容:
componentDidMount() {
const context = this.refs.canvas.getContext('2d');
this.setState({ context: context });
}
答案 0 :(得分:0)
使用require
加载图像,不要在render
中添加侦听器(如onload,onError等),请在componentDidMount中进行。
代码段
import React from "react";
import "./styles.css";
export default class App extends React.Component {
state = {};
ref = React.createRef(null);
componentDidMount() {
const context = this.ref.current.getContext("2d");
const image = new Image();
image.onload = function(res) {
console.log("res", res);
context.drawImage(image, 0, 0);
};
image.onerror = function(err) {
console.log("err", err);
};
image.src = require("./tree.jpeg");
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<canvas ref={this.ref} />
</div>
);
}
}