好的,这里是我的代码完美工作,正如它应该的那样。在函数中访问全局变量
function setCanvasBackground (src){
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destin_ctx.drawImage(source, 0, 0, img.width/4, img.height/4);
}
img.src = src;
};
但是,如果我移动的变量之外的功能,这样他们就可以从其他函数访问,代码只是不工作。这里是我做的:
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
function setCanvasBackground (src){
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destin_ctx.drawImage(source, 0, 0, img.width/4, img.height/4);
}
img.src = src;
};
所有的JavaScript代码都是单独的文件,而不是HTML。我在这里做错了什么?
可能试图选择尚未加载到DOM中的元素。首先你应该看看你的浏览器的开发者控制台。 –
您可以通过_assigning_值将其修改为setCanvasBackground中的全局变量,或者在window.onload或document/ready处理程序中执行。 – 2013-07-31 00:11:18
你可以在JSFiddle上重现正在运行的示例吗? – hugomg