所以我已经加载了图像,并且可以在本地访问该函数中的属性,例如 ball.height 和 width,但我需要在其他函数中使用这些属性来进行计算。我将如何访问这些属性,因为它们当前仅在本地定义。我无法将其设置为全局(或者至少不知道如何设置),因为为了首先获取图像,我必须使用函数加载它。
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);
关于javascript - 如何全局访问使用 JavaScript 加载的图像的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46461010/