Why are these variables “undefined”?

后端 未结 1 687
慢半拍i
慢半拍i 2021-01-24 01:02

I have the folowing code :

var canvasData;
var canvas2imgval;

imageObj1.onload = function() {
    ctx.drawImage(imageObj1, 0, 0, wdOb1, hgOb1);
    imageObj2.on         


        
相关标签:
1条回答
  • 2021-01-24 01:54

    You assign values to these variables in image onload event handlers, but try to access them before these handlers are executed.

    In order to use these variables you could create a function that will be called after imageObj2.onload executes. I'd also suggest to pass the canvasData as an argument instead of using a global variable (as long as it's not used elsewhere).

    var canvas2imgval;
    var afterLoad = function(canvasData){
        console.log("canvasData : "+canvasData ); 
        $("#canvas2img").val(canvasData) ;
        canvas2imgval = $("#canvas2img").val() ;
        console.log("canvas2imgval1 : "+canvas2imgval); 
    }    
    
    imageObj1.onload = function() {
    ctx.drawImage(imageObj1, 0, 0, wdOb1, hgOb1);
        imageObj2.onload = function() {
            ctx.drawImage(imageObj2, imgposLeft, imgposTop, wdOb2, hgOb2);
            //img = c.toDataURL("image/png");
            ////////document.write('<img src="' + img + '" width="256" height="256"/>');
            //canvas2img
            canvasData = c.toDataURL("image/png");
            afterLoad(canvasData);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题