2015-10-25 52 views
0

我已經創建了像大多數人一樣的彈跳球遊戲,當我點擊球時我想改變顏色。我看到很多關於如何製作我所做的教程,但沒有告訴我如何做我想做的事。有沒有人有任何想法可以幫助我。這裏是我的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>

回答

0

我叉你JSFiddle,它似乎工作至今,但東西是錯誤的測試,如果該點位於圓內。

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

得到了here的算法。

+0

也許你可以幫助這個,它在jsfiddle中很好用,但在本地不起作用。顏色不會改變。有任何想法嗎?我更新了jsfiddle順便說一句 –