nitish roy
nitish roy

Reputation: 21

javascript ball bouncing in html canvas

I am working with a javascript file which bounces a ball from four walls. I want to change the color of the ball when it hits the wall... for that I am trying two consecutive ifs but the second if is not getting executed I don't know why

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var  ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
if(dx>0){
    alert("dx is greater than 0");
}
if(dx<0){
    alert("dx is less than 0");
}
function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
    }
    if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
    }
    x += dx;
    y += dy;
}
setInterval(draw, 10);

Upvotes: 1

Views: 179

Answers (3)

user3013823
user3013823

Reputation: 211

I think maybe canvas.height is less than ballRadius then the 2nd part won't work.

Upvotes: 0

Amit Sheen
Amit Sheen

Reputation: 249

Just added a color var that updates whenever the ball changes direction.

color = '#' + Math.round(Math.random() * 15000000).toString(16);

Works great: https://jsfiddle.net/hsj8cvko/

Upvotes: 0

Spark_Chicken
Spark_Chicken

Reputation: 11

You check your if statements outside of the loop. The if statements are checked only once. In the initial conditions, dx>0, which calls one alert statement. But the "if" blocks are never called again.

if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
//######## NEW CODE #############
    if (dx > 0) {
        alert('Greater than zero');
    } else {
         alert('Less than zero');
    }
//################################

}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
    dy = -dy;
}

Upvotes: 1

Related Questions