Travis Travis - 1 year ago 33
CSS Question

How to create an ever-ending loop of an animated shape with canvas?

I have been messing around with canvas lately, and I came across a hurdle that I can't really overcome. I learned how to create shapes, animate them, and loop the same shape through the whole canvas (whether its x or y). It's hard to explain, but I cannot figure out how to spawn another shape behind the first one after a set amount of time. I want it to pretty much be a grid of squares moving horizontally.

I wanted to find some way to put that whole for loop with the code for the shape into a variable and then make a

to spawn the whole thing again after a certain amount of milliseconds, but I don't know if that would work.

function draw(x,y) {
// Put canvas in variable
var canvas = document.getElementById('canvas');
// Enable drawing
var ctx = canvas.getContext('2d');
// Start drawing;
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);
x += 0.3;
var loopTimer = setTimeout('draw('+x+', '+y+')', 0.1);


canvas {
margin-left: 200px;
width: 550px;
height: 400px;
border: 1px solid #111111;

<canvas id="canvas"></canvas>

Answer Source

You might want to create a square Class so you can create new objects on the fly.

function squareClass () {

  this.X = 0;
  this.Y = 0;

  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);

Now you can just use the square class to create all the squares you need.

var squareList = [];

function createASqaure() {

  squareList.push(new squareClass());

Calling the createASquare class will produce new squares.

In order to use the functions inside of the squares you can simply loop through the squareList array and call the functions like so

function moveAndDraw() {

  for (var i = 0; i < squareList.length; i++) {