2016-01-20 71 views
0

我正在使用HTML和JavaScript來製作遊戲,而我一直在這一段時間停留在這一段時間這段代碼是關於讓敵人從屏幕的一側移動到另一側不是問題,因爲我已經完成了它與其他字符。最大的問題是我無法克隆它們並使它們獨立移動。獨立javascript的同時移動同一個圓圈?

var canvas = document.getElementById('canvas'); 
 
var h = canvas.height; 
 
var w = canvas.width; 
 
var ctx = canvas.getContext("2d"); 
 
var x = w 
 
var y = Math.floor((Math.random() * 500) + 1); 
 

 
clear(); 
 
circleE(); 
 

 
function clear(){ 
 
    ctx.fillStyle = "Blue" 
 
    ctx.fillRect(0, 0, w, h) 
 
} 
 

 
function circleE(){ 
 
    ctx.fillStyle = "Pink"; 
 
    ctx.beginPath(); 
 
    ctx.arc(x,y,15,0,Math.PI*2,false); 
 
    ctx.closePath(); 
 
    ctx.fill(); 
 
}
<canvas id="canvas" width="1000" height="500" style="border:1px solid #000000;"></canvas>

回答

3

因爲它們共享x和y座標,所有克隆將在完全相同的空間呈現。每個圓圈都需要有自己的座標。

var canvas = document.getElementById('canvas'); 
 
    var h = canvas.height; 
 
    var w = canvas.width; 
 
    var ctx = canvas.getContext("2d"); 
 

 
    clear(); 
 
    
 
    function clear(){ 
 
     ctx.fillStyle = "Blue" 
 
     ctx.fillRect(0, 0, w, h) 
 
    } 
 

 
    function circleE(){ 
 
     var x = Math.floor((Math.random() * w) + 1); 
 
     var y = Math.floor((Math.random() * h) + 1); 
 
     ctx.fillStyle = "Pink"; 
 
     ctx.beginPath(); 
 
     ctx.arc(x,y,15,0,Math.PI*2,false); 
 
     ctx.closePath(); 
 
     ctx.fill(); 
 
    }
<button onclick="circleE()">Spawn</button><br> 
 
<canvas id="canvas" height="200" width="300"></canvas>

+0

我將如何做到這一點我想一個數組,但我沒有什麼ü建議 –

+0

你想去多麼複雜,什麼界需要做的依賴。我只是在我的代碼片段中隨機化了x和y,但是您可以創建一個圓形對象,並且每個對象都將具有座標作爲其屬性。這就是你在爲多個圈子設置動畫的情況下理想的做法。 – Shomz

+0

很久以前,我爲與您不相似的問題寫了一個答案,但實際的解決方案可能會幫助您,請參閱此處:http:// stackoverflow.com/a/34265601/965907 – Shomz