访问函数中的全局变量

Accessing global variable in function

本文关键字:全局变量 函数 访问      更新时间:2023-09-26

好的,这是我的代码,它运行得很好,就像它应该的那样

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);
});