0

I have created a bouncing ball game like most people have, I want to change the color when I click on the ball. I see a lot of tutorials on how to make what I have made but nothing showing me how to do what I want. Does anyone have any ideas that could help me out. Here is my jsfiddle

var ball;
var x = 100;
var y = 200;
var dx = 3;
var dy = 3.5;

function init() {
    ball = myCanvas.getContext('2d');
    setInterval(draw, 12);
    canvas.addEventListener('mousemove', ev_mousemove, false);
}

function draw() {
    ball.clearRect(0, 0, 600, 500);
    ball.beginPath();
    ball.fillStyle = " #F7742C";
    // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
    ball.arc(x, y, 10, 0, Math.PI * 2, true);
    ball.closePath();
    ball.fill();
    // Boundary Logic
    if (x < 10 || x > 590) dx = -dx;
    if (y < 10 || y > 490) dy = -dy;
    x += dx;
    y += dy;
}
<body onLoad="init();">
    <canvas id="myCanvas" width="600" height="500" style="border:10px solid"></canvas>
</body>

1 Answers1

0

I forked your JSFiddle and it seems to work so far but something is wrong with the test if the point is inside the circle.

<script>
    var ball;
    var x = 100;
    var y = 200;
    var dx = 3;
    var dy = 3.5;
    var color = " #F7742C";

    function init() {
        ball = myCanvas.getContext('2d');
        setInterval(draw, 12);
        myCanvas.addEventListener('click', ev_click, false);
    }

    function draw() {
        ball.clearRect(0, 0, 600, 500);
        ball.beginPath();
        ball.fillStyle = color;
        // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
        ball.arc(x, y, 10, 0, Math.PI * 2, true);
        ball.closePath();
        ball.fill();
        // Boundary Logic
        if (x < 10 || x > 590) dx = -dx;
        if (y < 10 || y > 490) dy = -dy;
        x += dx;
        y += dy;
    }

    function ev_click(e) {
        console.log(e.clientX+ " : " + e.clientY);
        console.log(x+  " : " + y);
        var inCircle= (e.clientX - x)*(e.clientX - x) + (e.clientY - y)*(e.clientY - y);
        console.log(inCircle);
        if ( inCircle< 2000) {
            color = " #000000";
        }
    }

</script>
<body onLoad="init();">
    <canvas id="myCanvas" width="600" height="500" style="border:10px solid"></canvas>

Got the algorithm from here.

Community
  • 1
  • 1
k4yaman
  • 475
  • 8
  • 20
  • Maybe you can help with this, it works great in jsfiddle but does not work locally. The color does not change. Any ideas? i updated the jsfiddle btw – CS Studentzzz Oct 25 '15 at 19:49