簡體   English   中英

訪問函數中的全局變量

[英]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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM