0

So, I just started javascript and everything was working fine till i came to objects. This peace of code is supposed to create a bouncing ball in a html canvas with javascript but it doesn't work.

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

//clear

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

here is my ball object

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

};

code to draw my ball

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

}

set interval

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

init();
1
  • I take it youre sure you have the canvas there in html? Commented Jun 12, 2012 at 22:45

1 Answer 1

2

Use this to reference the properties of the object on which the method is invoked.

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

Also, to call methods, you need to use ().

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

Otherwise you're passing the method instead of the result of calling the method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.