Reputation: 1037
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
.
Upvotes: 1
Views: 171
Reputation: 36995
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);
}
}
Upvotes: 1