简体   繁体   中英

How to globally access properties of an image loaded in with JavaScript

So I have loaded in an image and can access the properties within this function locally such as ball.height and width, but I need to use these properties in other functions to do calculations with. How would I access these properties since they are only locally defined currently. I can't set it as global (or at least don't know how) since in order to get the image in the first place I have to load it in with the function.

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
}

Since the image load is a asynchronous task, you can use a callback:

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

Create a global variable globalBall and once the image is loaded you can assign the image from the function to the global object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM