在函数中访问全局变量

时间:2013-07-31 00:05:08

标签: javascript canvas html5-canvas

好的,所以这是我的代码完美正常运行。

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。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

试试这个:

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){ 
    // ...
};

您无法在加载元素之前访问它们。这将导致尝试访问不存在的元素。

答案 1 :(得分:0)

您可以做的一件事是在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);
});