2

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?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
roger_that
  • 9,493
  • 18
  • 66
  • 102
  • You can't do this with CSS. You would have to change the fill color in JS (like `context.fillStyle='red'`) as the ball is a Canvas drawing. – Harry Oct 01 '15 at 07:58
  • How to do that? I mean generating random color with every fill. – roger_that Oct 01 '15 at 07:59

1 Answers1

6

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;
}
Community
  • 1
  • 1
nowhere
  • 1,558
  • 1
  • 12
  • 31
  • Can you be more clear? I've tried it here and seems to be working perfectly: https://jsfiddle.net/e0b1gkc4/4/ – nowhere Oct 01 '15 at 08:05
  • I guess I was actually wrong, but that's quite interesting ;-) going to investigate. – Amit Oct 01 '15 at 08:06
  • @Amit ok let me know if there really is something wrong ;) – nowhere Oct 01 '15 at 08:11
  • 1
    @nowhere - validated, your solution is solid. my fear (assumption really) was that calling `getContext()` returns a new object every time and that this new object doesn't maintain previous styles. what I [found out](http://www.w3.org/TR/html5/scripting-1.html#dom-canvas-getcontext) is that it *has* to return the same object, thus will maintain style. – Amit Oct 01 '15 at 08:21