JSFiddle - React, Tailwind, and code Playground
by rwachtler
HTML
<canvas id="myCanvas" width="500" height="500">
<!-- Insert fallback content here -->
</canvas>
CSS
canvas {
border:1px solid #CCCCCC;
}
canvas.over{
background: red;
}
JavaScript
//Canvas
theCanvas = document.getElementById("myCanvas");
context = theCanvas.getContext("2d");
context.fillStyle = '#EEEEEE';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
var asteroids = new Array();
var gameLoop;
var collision;
var SpaceObject = function (width, height) {
this.x = Math.floor((Math.random() * theCanvas.width) + 1);
this.y = Math.floor((Math.random() * theCanvas.height) + 1);
this.width = width;
this.height = height;
this.velocity = Math.random(5, 11);
return this;
};
var p1 = new SpaceObject(20, 20);
p1.x = 0;
p1.y = theCanvas.height / 2 - p1.height / 2;
p1.velocity = 20;
SpaceObject.prototype.draw = function (fillStyle) {
context.fillStyle = fillStyle || '#000000';
context.fillRect(this.x, this.y, this.width, this.height);
};
SpaceObject.prototype.resetX = function () {
x = theCanvas.width;
return x;
}
SpaceObject.prototype.resetY = function () {
y = Math.floor((Math.random() * theCanvas.height) + 1);
return y;
}
function setup() {
window.addEventListener("keydown", keyPress, true);
var i = 5;
do {
asteroids.push(new SpaceObject(30, 30));
} while (i--);
p1.draw();
}
$(document).ready(function () {
setup();
function draw() {
//clear canvas
context.fillStyle = '#EEEEEE';
context.clearRect(0, 0, theCanvas.width, theCanvas.height);
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
for (i = 0; i < asteroids.length; i++) {
if (asteroids[i].x - asteroids[i].velocity < 0) {
asteroids[i].x = asteroids[i].resetX();
asteroids[i].y = asteroids[i].resetY();
collide();
} else {
asteroids[i].x -= asteroids[i].velocity;
}
asteroids[i].draw('#F22613');
}
p1.draw();
}
function start() {
gameLoop = window.setTimeout(start, 30);
collision =...