访问函数中的全局变量
Accessing global variable in function
好的,这是我的代码,它运行得很好,就像它应该的那样
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中。我在这里做错了什么?
试试这个:
var source, source_ctx, destination, destin_ctx;
window.onload=function() {
source = document.getElementById('hiddenCanvas');
source_ctx = source.getContext('2d');
destination = document.getElementById('visibleCanvas');
destin_ctx = destination.getContext('2d');
}
function setCanvasBackground (src){
// ...
};
在加载图元之前,不能访问这些图元。这将导致尝试访问不存在的元素。
您可以做的一件事是将回调添加到setCanvasBackground:中
function setCanvasBackground(src, callback) {
[...snip...]
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);
// all set now:
callback(source, source_ctx, destination, destin_ctx);
}
[...snip...]
}
然后,当您调用setCanvasBackground时,添加一个在图像加载完成之前不会调用的函数:
setCanvasBackground(..., function(src, src_ctx, dest, dest_ctx) {
alert("source.width: " + src.width);
});
相关文章:
- 在javascript函数中设置全局变量
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- 创建要在其他函数中使用的全局变量
- 函数中的innerHTML(全局变量?)
- 全局变量只能由第一个函数访问
- 匿名自执行js函数内部的全局变量在外部仍然可用
- 更改函数内部的全局变量而不调用它
- 如何制作全局javascript函数和变量
- 改进js代码以删除全局变量和函数
- 调用函数后如何重置全局变量
- 无法在函数中检索全局变量的值
- 将全局变量传递给自调用函数或“IIFE”的目的
- 保留 JQuery Vars 用于另一个函数(全局变量?)
- 如何在 ajax 调用后更改包装器 JavaScript 函数中的全局变量
- 删除两个函数使用的全局变量
- 如何将socket.on中函数的值保存为全局变量
- angular/javascript无法识别函数内部的全局变量
- Javascript测试存根全局变量函数
- 在JavaScript中添加一个全局变量/函数(特别是NativeScript)
- Javascript从本地向全局变量函数添加行