2013-07-31 199 views
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。我在这里做错了什么?

+7

可能试图选择尚未加载到DOM中的元素。首先你应该看看你的浏览器的开发者控制台。 –

+2

您可以通过_assigning_值将其修改为setCanvasBackground中的全局变量,或者在window.onload或document/ready处理程序中执行。 – 2013-07-31 00:11:18

+0

你可以在JSFiddle上重现正在运行的示例吗? – hugomg

回答

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

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

+0

我只是做了同样的改变 - 我在window.onload函数中声明了变量,但它完美地工作 –

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