Setting img.src in componentDidUpdate cannot trigger img.onload event callback

componentDidUpdate(prevProps, prevState, snapImg){
    if(this.props.bookImg!=null && this.props.bookImg!==prevProps.bookImg){
        var canvas= document.createElement("canvas");
        var ctx= canvas.getContext("2d");
        var img= new Image();
        img.crossOrigin= "Anonymous";
        var dataURL;
        img.onload=function() {
            console.log("fn");
            ctx.drawImage(img, 0, 0);
            dataURL= canvas.toDataURL("image/jpeg");
            console.log(dataURL);
        }
        img.src=this.props.bookImg;
        console.log("end");
    }
}

this code is valid when I test it in the < script > tag, but the callback used in componentDidUpdate img.onload cannot be triggered; does anyone know why?

Jul.08,2021

initializing the first rendering of the lifecycle will not be performed, so it should not be onload that does not execute, but not the whole one, right?

if it is not the first time to render, then you need to post the feasible code written in your script to analyze

.
  1. confirm that componentDidUpdate executes successfully
  2. make sure src does exist
  3. check network to see if the picture is successful load
  4. check whether console has cross-domain errors

I have just tried the code. Except for a cross-domain error in setting crossOrigin, I can successfully execute the onload function


I modified the code several times and found it was OK. I posted the code below:

componentDidUpdate(prevProps, prevState){
    if(this.props.bookImg!=null && this.props.bookImg!==prevProps.bookImg){
        var bookId= this.props.bookId;
        var _this= this;
        var canvas= document.createElement('canvas');
        var ctx= canvas.getContext('2d');
        var img= document.createElement('img'); //new Image() not work! ??????
        img.crossOrigin= 'Anonymous';
        var dataURL;
        img.onload=function() {
            canvas.width= img.width;
            canvas.height= img.height;
            ctx.drawImage(img, 0, 0);
            dataURL= canvas.toDataURL("image/jpeg");
            var info={id: bookId, url: dataURL};
            _this.props.actions.UpdateDataURL(info);
        }
        img.src=this.props.bookImg;
    }
}

it seems that it would be fine to use new Image to generate img objects instead of document.createElement ('img'); but I still don't know why.

Menu