簡體   English   中英

如何使用Javascript和Canvas不斷生成運動形狀

[英]How to constantly generate a moving shape with Javascript and Canvas

我目前正在為頂峰項目開發一款小型游戲。 在游戲中,用戶嘗試以設定的速度避免從屏幕右側向左側移動隨機大小的矩形。

它是使用面向對象的Javascript構建的,並且為它分配了一個匿名函數,但是,我似乎沒有比最初調用該函數時更能生成形狀並對其進行動畫處理。 如果創建多個對象,則可以解決該問題,但是我希望此函數自動運行並生成不僅僅是第一個矩形的對象。

我試圖用一個間隔調用該函數,以強制它重新運行該函數,但沒有結果。 我還嘗試將初始化函數與參數分開,以生成賦予它的形狀數量。

該函數可通過初始調用生成形狀,並確定顏色,大小和位置,並將其繪制在畫布上。

var randomRectangle = function(){
this.init = function() {
this.speed = 4;
this.x = canvas.width-50;
this.y = Math.floor(Math.random()*280) + 40;
this.w = Math.floor(Math.random()*200) + 50;
this.h = Math.floor(Math.random()*150) + 20;
this.col = "#b5e61d";
}
this.move = function(){
this.x -= this.speed;
}

this.draw = function(num){
draw.rectangles(this.x, this.y, this.w, this.h, this.col);
}
};

在此初始化對象,然后循環在畫布上生成所有對象和動畫。

randRecs = new randomRectangle();
randRecs.init();

function loop(){
draw.clear();

player.draw();
player.move();

wall1.draw();
wall2.draw();

randRecs.draw();
randRecs.move();


}


var handle = setInterval(loop, 30);

我期望矩形將在具有新尺寸的新y坐標處連續生成,然后從屏幕的右側移至左側。 但是,只能創建一個矩形並對其進行動畫處理。

 var list = []; var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); var randomRectangle = function() { this.init = function() { this.speed = 4; this.x = canvas.width - 50; this.y = Math.floor(Math.random() * 280) + 40; this.w = Math.floor(Math.random() * 200) + 50; this.h = Math.floor(Math.random() * 150) + 20; this.col = "#b5e61d"; } this.move = function() { this.x -= this.speed; // restart x position to reuse rectangles // you can change the y value here to a new random value // or you can just remove with array.splice if (this.x < -50) this.x = canvas.width - 50; } this.draw = function(num) { draw.rectangles(this.x, this.y, this.w, this.h, this.col); } }; function loop() { draw.clear(); //player.draw(); //player.move(); //wall1.draw(); //wall2.draw(); // call the methods draw and move for each rectangle on the list for (var i=0; i<list.length; i++) { rec = list[i]; rec.draw(); rec.move(); } } // spawn any number of new rects in a specific interval var rectsPerSpawn = 1; function addRects() { for (var i=0; i<rectsPerSpawn; i++) { if (list.length < 100) { var rec = new randomRectangle(); list.push(rec); rec.init(); } } } // every half second will spawn a new rect var spawn = setInterval(addRects, 500); var draw = { clear: function () { ctx.clearRect(0,0,canvas.width,canvas.height); }, rectangles: function (x, y, w, h, col) { ctx.fillStyle = col; ctx.fillRect(x,y,w,h); } } var handle = setInterval(loop, 30); 
 <canvas></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM