react canvas画布图片显示不出来的解决方案

可能的原因:

  1. 图片未获取到
  2. 图片获取到了,但是在context.drawImage前还没加载出来

代码

class Canvas extends Component {
    
    
    
    constructor(props) {
    
    
        super();
        this.canvas1 = React.createRef();
        this.canvas2 = React.createRef();
        this.image = new Image();
        this.image.src = require('./img/龙山骨刻内文6_14.png');
        this.state = {
    
    
            savedImage: null,
        }
    }

    // 组件完成挂载后
    componentDidMount(){
    
    
        let ctx = this.canvas1.current.getContext('2d');//获取上下文
        let ctx2 = this.canvas2.current.getContext('2d');
        // 解决:图片加载完毕后再调用 ctx.drawImage
        this.image.onload=()=>{
    
    
            ctx.drawImage(this.image, 0, 0, this.canvas1.current.width, this.canvas1.current.height);
            ctx2.drawImage(this.image, 0, 0, this.canvas2.current.width, this.canvas2.current.height);
            }
    }
    
     render() {
    
    
        return (
            <div className="App">
               ...
                 <div className="canvasContainer">
                    <div className="canvasContainer2">
                        <canvas id="myCanvas" className="myCanvas" style={
    
    {
    
    zIndex: 1}} ref={
    
    this.canvas1}>
                            您的浏览器不支持canvas
                        </canvas>
                        <canvas id="myCanvas2" className="myCanvas"
                                style={
    
    {
    
    zIndex: -1, position: "absolute", display: "none"}}
                                ref={
    
    this.canvas2}>
                            您的浏览器不支持canvas
                        </canvas>
                    </div>
                </div>
            </div>
        );
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45830447/article/details/124023209