2012-06-12 162 views
0

所以,我刚开始使用JavaScript,并且一切都很好,直到我来到对象。 代码的这种安宁应该创造一个JavaScript的HTML画布中的弹跳球,但它不起作用。访问javascript中的对象变量

var canvas = document.getElementById("myCanvas"); 
    var ctx = canvas.getContext("2d"); 

//clear 

function clear() { 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
} 

这里是我的球对象

//ball 

var ball = { 

x: canvas.width/2, 
getX: function() { 
    return this.x; 
}, 
setX: function(a) { 
    this.x = a; 
}, 

y: canvas.height/2, 
getY: function() { 
    return this.y; 
}, 
setY: function(a) { 
    this.y = a; 
}, 

mx: 2, 
getMx: function() { 
    return this.mx; 
}, 
setMx: function(a) { 
    this.my = a; 
}, 
my: 4, 

getMy: function() { 
    return this.my; 
}, 

setMy: function(a) { 
    this.my = a; 
}, 
r: 10, 
getR: function() { 
    return this.r; 
} 

};

代码绘制我的球

function drawBall() 
{ 
    ctx.beginPath(); 
    ctx.arc(ball.getX, ball.getY, ball.getR, 0, Math.PI * 2, true); 
    ctx.fillStyle = "#83F52C"; 
    ctx.fill(); 

} 

function circle(x, y, r) { 
    ctx.beginPath(); 
    ctx.arc(x, y, r, 0, Math.PI * 2, true); 
    ctx.fillStyle = "#83F52C"; 
    ctx.fill(); 
} 
//draws ball and updates x,y cords 
function draw() { 
    clear(); 
    drawBall(); 
    if (ball.getX() + ball.getMx() >= canvas.width || ball.getX()+ ball.getMx() <= 0) { 
     ball.setMx(-ball.getMx()); 
    } 
    if (ball.getY() + ball.getMy() >= canvas.height|| ball.getY()+ ball.getMy() <= 0) { 
     ball.setMy(-ball.getMy()); 
    } 

    ball.setX(ball.getX() + ball.getMx()); 
    ball.setY(ball.getY() + ball.getMy()); 

} 

设定间隔

function init() { 
    return setInterval(draw, 10); 
} 

init(); 
+0

我认为你确定你有在HTML中的画布? – Alex

回答

2

使用this引用在其上调用方法的对象的属性。

var ball = { 

    x: canvas.width/2, 
    getX: function() { 
     return this.x; 
    }, 
    setX: function(a) { 
     this.x = a; 
    }, 

    y: canvas.height/2, 
    getY: function() { 
     return this.y; 
    }, 
    setY: function(a) { 
     this.y = a; 
    }, 

    mx: 2, 
    getMx: function() { 
     return this.mx; 
    }, 
    my: 4, 
    getMy: function() { 
     return this.my; 
    }, 
    r: 10, 
    getR: function() { 
     return this.r; 
    } 
}; 

此外,要调用方法,您需要使用()

ctx.arc(ball.getX(), ball.getY(), ball.getR(), 0, Math.PI * 2, true); 

否则,你传递的方法,而不是调用该方法的结果。

+0

它现在有效,谢谢 – user1452370

+0

@ user1452370:不客气。 – 2012-06-12 22:48:44