在javascript中访问对象变量
所以,我刚开始使用javascript,在使用对象之前,一切都很好。 这种代码的和平应该是用javascript在html画布中创建一个弹跳球,但它不起作用在javascript中访问对象变量,javascript,html,canvas,Javascript,Html,Canvas,所以,我刚开始使用javascript,在使用对象之前,一切都很好。 这种代码的和平应该是用javascript在html画布中创建一个弹跳球,但它不起作用 var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); //clear function clear() { ctx.clearRect(0, 0, canvas.width, canvas.height);
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());
}
使用
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;
}
};
另外,要调用方法,您需要使用()
否则,您将传递该方法,而不是调用该方法的结果。我认为您确定画布是html格式的吗?
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);