1

I have the folowing code :

var canvasData; var 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"); } } console.log("canvasData : "+canvasData ); $("#canvas2img").val(canvasData) ; canvas2imgval = $("#canvas2img").val() ; console.log("canvas2imgval1 : "+canvas2imgval ); 

The problem is when I view the value of both variables, canvasData is undefined and canvas2imgval1 has no value. I don't know what's wrong with my code. Normally those two variables are marked public with the JavaScript keyword var.

7
  • canvasData = c.toDataURL("image/png"); What is c? canvas2imgval = $("#canvas2img").val() ; Does that element exist? Commented Jul 24, 2013 at 9:51
  • You assign values to these variables in image onload event handlers, but try to access them before these handlers are executed. Commented Jul 24, 2013 at 9:52
  • you use these variable before imageObj1 is loaded. This is HTTP request, your browser will load HTML then javascript then other objects. Commented Jul 24, 2013 at 9:52
  • These two variables are not going to have values until imageObj1's onload event runs. If you are looking at their values immediately after assigning a function to imageObj1.onload, then they will be undefined. Commented Jul 24, 2013 at 9:53
  • the c variable it is the variable holding the canvas element that i want to merge on it my two images : Commented Jul 24, 2013 at 9:53

1 Answer 1

1

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.