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