1

好的,所以这是我的代码,它工作得很好,就像它应该做的那样。

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

4

2 回答 2

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

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

于 2013-07-31T00:24:44.180 回答
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);
});
于 2013-07-31T00:32:58.763 回答