I'm trying to create a simple javascript game and I'm running into a problem accessing a function's data outside of it.
This code works perfectly.
window.onload = function() {
var FPS = 30;
var ground = new myObject();
var twoground = new myObject();
setInterval(function() {
clear();
draw();
ground.draw(0, 325);
twoground.draw(125,325);
alert(ground.xval);
}, 1000/FPS);
};
function myObject(){
this.draw = function drawground(groundx, groundy){
this.xval=groundx+125;
this.yval = groundy;
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');
var img=new Image()
img.src="ground.png"
img.onload = function() {
context.drawImage(img,groundx,groundy)}
}
};
The above alerts 125 to the browser every time the interval runs, but that's the only way I can do it, for example if I do the following instead.
window.onload = function() {
var FPS = 30;
var ground = new myObject();
var twoground = new myObject();
setInterval(function() {
clear();
draw();
ground.draw(0, 325);
twoground.draw(125,325);
myalert();
}, 1000/FPS);
};
function myalert()
{
alert(ground.xval);
}
function myObject(){
this.draw = function drawground(groundx, groundy){
this.xval=groundx+125;
this.yval = groundy;
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');
var img=new Image()
img.src="ground.png"
img.onload = function() {
context.drawImage(img,groundx,groundy)}
}
};
What I would expect is the same thing, as it should be calling myalert, which only displays an alert, in the same interval, but it doesn't. I feel like I'm missing something with the way javascript functions work.