rudra
rudra

Reputation: 200

how to change the variable when onload is executed

I am trying to load an image in canvas. I want to get the variable when onload function is executed.

function getResponse(srcImg){

var img = new Image();
var loaded = false;
img.src = srcImg;

img.onload = function(){
  loaded = true;
  }
 // i want to get loaded variable when the onload function is complete
 // wait the return value until the img is not loaded
 return loaded;
}

getResponse(imageURL); //loaded is false

I have tried the following method also. But it is not working for me. The value that returned by the following method is undefined

function getResponse(srcImg,cb){

var img = new Image();
var loaded = false;
img.src = srcImg;

img.onload = function(){
  loaded = true;
  cb(loaded);
  }
 // i want to get loaded variable when the onload function is complete
 // wait the return value until the img is not loaded
 return loaded;
}

getResponse(imageURL,output(load)); //output is undefined

function output(load){
console.log(load);
}

Upvotes: 0

Views: 1506

Answers (2)

use callback like this

function init(){
    var srcImg = "https://cdn.shopify.com/s/files/1/1447/4928/products/large_grande.jpg"
    getSource(srcImg,(data)=>{
        //do your process here
        document.getElementById("demo").textContent = data
    });
}
    
function getSource(src,callback){
    var img = new Image();
    img.onload = function(){
	callback(src);
    }
    img.src = src;
}
<body onload="init()">
	<p id="demo"></p>
</body>

Upvotes: 0

sinbar
sinbar

Reputation: 1063

That is a async behavior. You may use a callback or promise. look below:

function getResponse(srcImg,callback){

    var img = new Image();
    var loaded = false;
    img.src = srcImg;

    img.onload = function(){
      loaded = true;
      callback(loaded)
      }
     // i want to get loaded variable when the onload function is complete
     // wait the return value until the img is not loaded
     return loaded;
}

getResponse(imageURL,(load)=>{});

Upvotes: 1

Related Questions