JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="400" height="400"></canvas>
CSS
#canvas{
border:solid 1px #000;
margin:10px;
}
JavaScript
(function(){
var canvas = $("#canvas")[0];
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var player1, player2, player3;
function Projectile(pos, dx, dy){
this.pos = {x:pos.x, y:pos.y};
this.dx = dx;
this.dy = dy;
var me = this;
this.draw = function(ctx){
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(me.pos.x, me.pos.y, 10, 0, Math.PI * 2, false);
ctx.fill();
me.pos.x += me.dx;
me.pos.y += me.dy;
};
}
function Player(pos, frate/* Shots per second */){
this.pos = pos;
this.projectiles = [];
this.fireRate = frate;
var me = this;
var lastFire = new Date();
this.draw = function(ctx){
ctx.fillStyle = "#000";
ctx.fillRect(this.pos.x - 32, this.pos.y - 32, 64, 64);
for (var i = 0; i < me.projectiles.length; i++){
var pro = me.projectiles[i];
if (pro){
pro.draw(ctx);
if (pro.pos.x - 32 > width){
delete me.projectiles.shift();
}
}
}
};
this.move = function(dx, dy){
this.pos.x += dx;
this.pos.y += dy;
};
this.fire = function(){
var cFire = new Date();
if ((cFire - lastFire) / 1000 > 1/me.fireRate){
me.projectiles.push(new Projectile(me.pos, 10, 0));
lastFire = cFire;
}
};
}
var draw = function(){
context.clearRect(0,0,width,height);
player1.draw(context);
player2.draw(context);
player3.draw(context);
webkitRequestAnimationFrame(draw);
...