如何使用Javascript和Canvas不断生成运动形状

时间:2019-04-15 19:34:18

标签: javascript html5-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坐标处连续生成,然后从屏幕的右侧移至左侧。但是,只能创建一个矩形并对其进行动画处理。

1 个答案:

答案 0 :(得分:0)

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>