如何全局访问用JavaScript加载的图像的属性
因此,我已经加载了一个图像,可以在本地访问此函数中的属性,例如ball.height和width,但我需要在其他函数中使用这些属性来进行计算。我如何访问这些属性,因为它们当前仅在本地定义。我无法将其设置为全局(或者至少不知道如何设置),因为为了首先获得图像,我必须将其与函数一起加载如何全局访问用JavaScript加载的图像的属性,javascript,jquery,html,Javascript,Jquery,Html,因此,我已经加载了一个图像,可以在本地访问此函数中的属性,例如ball.height和width,但我需要在其他函数中使用这些属性来进行计算。我如何访问这些属性,因为它们当前仅在本地定义。我无法将其设置为全局(或者至少不知道如何设置),因为为了首先获得图像,我必须将其与函数一起加载 function drawBall() { var ball = new Image(); $(ball).on('load', function() { ctx.drawImage(ball, xB
function drawBall() {
var ball = new Image();
$(ball).on('load', function() {
ctx.drawImage(ball, xBall, yBall);
console.log(ball.height);
});
ball.src = 'ball.png';
}
function ballHit() {
// For example calculate if ball.height = canvas.height
}
由于映像加载是一项异步任务,因此可以使用回调:
function drawBall(callback) {
var ball = new Image();
$(ball).on('load', function() {
ctx.drawImage(ball, xBall, yBall);
console.log(ball.height);
callback(ball.height,ball.width);
});
ball.src = 'ball.png';
}
drawBall(ballHit);
创建一个全局变量globalBall,加载图像后,可以将函数中的图像指定给全局对象
var globalBall = new Image();
function drawBall() {
var ball = new Image();
$(ball).on('load', function() {
ctx.drawImage(ball, xBall, yBall);
console.log(ball.height);
});
ball.src = 'ball.png';
globalBall = ball;
}
function ballHit() {
if(globalball.height == canvas.height)
{
// Do your stuff
}
}
您可以将此Ball对象存储为全局对象,然后访问JavaScript在词汇范围内的任何位置。只需将变量放在更高的级别,去掉关键字
var
,不要在函数中使用该var
名称作为参数。谁在调用ballHit
?有很大不同。@JuanMendes它将在另一个函数draw()中调用。@VincentNguyen那么,谁调用draw()
?要点是,理想情况下,您可以在调用之间将数据作为参数传递(可能保留为闭包),而不是使用全局变量。我收到错误:TypeError:undefined不是对象(计算“globalBall.height”)。您可以创建Image类型的globalBall对象。无论我将其初始化为什么,赋值globalBall=ball代码>似乎没有按我预期的方式执行。回调应该是回调(ball)
是的,这取决于操作。