1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| var butterflyArray = [];
var ctx;
window.addEventListener('load', function () {
ctx = document.getElementById("canvas");
var line1 = new line({nb:1,
posX : 30,
posY: 30,
direction : -1,
minspace : 32,
maxspace : 96,
speed : 2});
for(var i=0;i<7;i++)
{
var butterfly = new animal(line1, 64);
butterflyArray.push(butterfly);
ctx.appendChild(butterfly.image);
}
}, false);
function line(elements)
{
this.nb = elements.nb;
this.direction = elements.direction;
this.minspace = elements.minspace;
this.maxspace = elements.maxspace;
this.speed = elements.speed;
this.posX = elements.posX;
this.posY = elements.posY;
this.lastanimal;
this.getNextPosX = function(animal)
{
var space = Math.floor(Math.random()*(this.maxspace-this.minspace)) + this.minspace;
var lastPosX = 0;
if (this.lastanimal)
{
lastPosX = this.direction == -1? this.lastanimal.posX + this.lastanimal.width + space : this.lastanimal.posX - space - animal.width;
}
else
{
lastPosX = this.posX;
}
this.lastanimal = animal;
return lastPosX;
}
}
function animal(myLine, width)
{
this.width = width;
this.myLine = myLine;
this.posY = this.myLine.posY;
this.posX = this.myLine.getNextPosX(this);
this.move = function()
{
this.posX = this.myLine.direction == 1? this.posX + this.myLine.speed : this.posX - this.myLine.speed;
if ((this.myLine.direction == 1 && this.posX >= 800) || (this.myLine.direction == -1 && this.posX < (-this.width)))
{
this.posX = this.myLine.getNextPosX(this);
}
}
this.draw = function()
{
this.image = new Image()
this.image.src = 'images/butterfly.png';
ctx.drawImage(this.image, this.posX, this.posY);
}
}
setInterval(function(){for (var e=0; e < butterflyArray.length;e++){butterflyArray[e].move(); butterflyArray[e].draw();}}, 80); |
Partager