好的,所以这是我的代码,它工作得很好,就像它应该做的那样。
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 中。我在这里做错了什么?