为什么这些变量“未定义”? [英] Why are these variables "undefined"?
问题描述
我有以下代码:
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 );
问题是当我查看两个变量的值时, canvasData
是未定义
和 canvas2imgval1
没有值。
我不知道我的代码有什么问题。通常这两个变量用JavaScript关键字 var
标记为公共。
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
.
推荐答案
您在图像 onload
事件处理程序中为这些变量赋值,但在执行这些处理程序之前尝试访问它们。
You assign values to these variables in image onload
event handlers, but try to access them before these handlers are executed.
为了使用这些变量,您可以创建一个在 imageObj2.onload
执行后调用的函数。我还建议将 canvasData
作为参数传递而不是使用全局变量(只要它没有在其他地方使用)。
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);
}
}
这篇关于为什么这些变量“未定义”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!