最近我一直在和 canvas 打交道,我遇到了一个我无法真正克服的障碍。我学会了如何创建形状、为它们设置动画,以及如何在整个 Canvas (无论是 x 还是 y)上循环相同的形状。很难解释,但我不知道如何在一定时间后在第一个形状后面生成另一个形状。我希望它几乎是一个水平移动的正方形网格。
我想找到一些方法将带有形状代码的整个 for 循环放入一个变量中,然后制作一个 setTimeout()
以在一定的毫秒数后再次生成整个循环,但我不知道这是否可行。
function draw(x,y) {
// Put canvas in variable
var canvas = document.getElementById('canvas');
// Enable drawing
var ctx = canvas.getContext('2d');
// Start drawing
ctx.save();
ctx.clearRect(0, 0, 550, 400);
for(var i = 0 ; i < 400 ; i+=10){
ctx.fillStyle = "rgb(0, 200, 0)";
ctx.fillRect(x, i, 5, 4);
}
ctx.restore();
x += 0.3;
var loopTimer = setTimeout('draw('+x+', '+y+')', 0.1);
}
draw(0,0);
canvas {
margin-left: 200px;
width: 550px;
height: 400px;
border: 1px solid #111111;
}
<canvas id="canvas"></canvas>
最佳答案
您可能想要创建一个方形类,以便您可以动态创建新对象。
function squareClass () {
//Position
this.X = 0;
this.Y = 0;
//Size
this.width = 5;
this.height = 4;
//Color to render
this.color = "rgb(0, 200, 0)";
//Move square
this.move = function() { this.X += 0.3; }
//Draw square
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.X, this.Y, this.width, this.height);
}
}
现在您可以使用 square 类来创建您需要的所有正方形。
var squareList = [];
function createASqaure() {
squareList.push(new squareClass());
}
调用 createASquare 类将生成新的正方形。
为了使用方 block 内部的函数,您可以简单地遍历 squareList 数组并像这样调用函数
function moveAndDraw() {
for (var i = 0; i < squareList.length; i++) {
squareList[i].move();
squareList[i].draw();
}
}
关于javascript - 如何使用 Canvas 创建动画形状的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544774/