javascript - HTML Canvas 创建多个动画矩形

标签 javascript html animation canvas

我正在尝试使用 Canvas 创建 HTML5 游戏,该游戏需要创建多个 block (每秒创建一个新 block )。每次创建新 block 时,它都需要使用动画“落”到屏幕上。我可以让动画在一个元素上正常工作,但我不确定如何创建多个元素(并以与动画 FPS 使用的时间间隔不同的时间间隔创建它们)。

//update and animate the screen
var FPS = 60;
setInterval(function() {
  //update();
  draw();
}, 1000/FPS);

var y = 30;
var dy = 5;

//5 + Math.floor(Math.random()*6)

//draw the screen
function draw() {
    //var y = 30;
    context.save();
    context.clearRect(0,0,canvas.width, canvas.height);
    rounded_rect(1*40, y, 40, 40, 5, "red", "black");
    if (this.y < 360){
        y += dy;
    }
    context.restore();

};

rounded_rect 只是另一个创建圆 Angular 矩形的函数。它工作正常。

最佳答案

<强> Live Demo

这是一种方法。创建一个数组来保存 block ,以及一个用于盒子的 block 对象。然后,我创建两个方法,更新和渲染,它们更新框并将其绘制到 Canvas 上。

block 对象

function Block(x,y,width,height){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

Block.prototype.update = function(){
    if(this.y < 360){
        this.y+=dy   
    }else{
        this.y = 0;   
    }
};

Block.prototype.render = function(){
    context.fillRect(this.x, this.y, this.width, this.height);
};

检查时间是否达到阈值

至于创建与帧速率无关的新 block ,您只需检查时间,看看自上次创建 block 以来是否已经过去了 1 秒。

if(+new Date() > lastTime + minWait){
    lastTime = +new Date();
    // add a new block
    blocks.push(new Block(Math.random()*300, 0,20,20));
}

基本上,它的工作原理是,如果当前时间大于上次时间 + 1 秒,它将创建一个新时间,并将上次时间重置为当前时间。

其他信息

我强烈建议您查看requestAnimationFrame这是进行任何类型的 Canvas 渲染的正确且事实上的方法。

完整来源

var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");

//update and animate the screen
var FPS = 60;
setInterval(function() {
  //update();
  draw();
}, 1000/FPS);

var dy = 5,
    blocks = [],
    minWait = 1000,
    lastTime = +new Date();

function Block(x,y,width,height){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

Block.prototype.update = function(){
    if(this.y < 360){
        this.y+=dy   
    }else{
        this.y = 0;   
    }
};

Block.prototype.render = function(){
    context.fillRect(this.x, this.y, this.width, this.height);
};

//draw the screen
function draw() {
    if(+new Date() > lastTime + minWait){
        lastTime = +new Date();
        blocks.push(new Block(Math.random()*300, 0,20,20));
    }

    context.clearRect(0,0,canvas.width, canvas.height);

        blocks.forEach(function(e){
            e.update();
            e.render();
        });
};

关于javascript - HTML Canvas 创建多个动画矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20527268/

相关文章:

ios - 在 SwiftUI 中,有没有办法扩展和收缩 View 以在 View 的扩展版本中显示隐藏的文本和按钮?

javascript - 将base64图像转换为jpeg

javascript - 通过按钮更改文字大小

javascript - 无法使用 Node.js 处理 PHP 文件

javascript - RestAngular:put 和 customPUT 正在发送旧对象,而不是更新对象

jquery - "Fly-in"jQuery 动画

javascript - 奇怪的 Angular ng-model 问题

javascript - 删除javascript中的div

javascript - 删除 Bootstrap 开关 HTML 元素

android - AnimateLayoutChanges 不适用于 RecyclerView