roger_that
roger_that

Reputation: 9791

CSS3: change the color of the ball every time it bounces off the canvas wall

I have to create a ball game in HTML5/CSS3. JSFiddle for the same could be seen.

Now what I want is to change the ball color every time it bounces off the wall.

var context;
var dx = 4;
var dy = 4;
var y = 150;
var x = 10;

function draw() {
  context = myCanvas.getContext('2d');
  context.clearRect(0, 0, 300, 300);
  context.beginPath();
  context.arc(x, y, 20, 0, Math.PI * 2, true);
  context.closePath();
  context.fill();
  if (x < 0 || x > 300)
    dx = -dx;
  if (y < 0 || y > 300)
    dy = -dy;
  x += dx;
  y += dy;
}

setInterval(draw, 10);
#container {
  text-align: center;
}
#myCanvas {
  background: #fff;
  border: 1px solid #cbcbcb;
  text-align: center;
}
<div id="container">
  <div>
    <canvas id="myCanvas" width="300" height="300"></canvas>
  </div>
</div>

I don't know how to do it. Can css3 be used to do this?

Upvotes: 2

Views: 3157

Answers (1)

nowhere
nowhere

Reputation: 1548

The random color function comes from here: https://stackoverflow.com/a/1484514/2042240

This will make it change at every bounce.

https://jsfiddle.net/e0b1gkc4/4/

var context;
var dx= 4;
var dy=4;
var y=150;
var x=10;
function draw(){
    context= myCanvas.getContext('2d');
    context.clearRect(0,0,300,300);
    context.beginPath();
    context.arc(x,y,20,0,Math.PI*2,true);
    context.closePath();
    context.fill();
    if( x<0 || x>300){
        dx=-dx;
        context.fillStyle = getRandomColor();
    }
    if( y<0 || y>300){
        dy=-dy;
        context.fillStyle = getRandomColor();
    }
        x+=dx;
        y+=dy;

}
setInterval(draw,10); 


function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

Upvotes: 6

Related Questions