JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="1350" height="600">Sorry, your browser doesn't support this</canvas>
CSS
#canvas { background-color: black; }
JavaScript
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var lives = 3;
var Enemy = function (x, y, velx, vely,transparency,speed) {
this.x = x;
this.y = y;
this.velx = 0;
this.vely = 0;
this.speed = speed;
this.transparency = 1;
};
Enemy.prototype.update = function () {
var tx = 650 - this.x;
var ty = 250 - this.y;
var dist = Math.sqrt(tx * tx + ty * ty);
this.velx = (tx / dist)* this.speed;
this.vely = (ty / dist)* this.speed;
var distround = Math.floor(dist);
if (distround > 0) {
this.x += this.velx;
this.y += this.vely;
} else if (this.transparency != 0){
alert("You lose!");
location.reload(true);
}
};
Enemy.prototype.isOnEnemy = function(x, y) {
return (x >= this.x && x < this.x + 25 && // 25 = width
y >= this.y && y < this.y + 25); // 25 = height
};
Enemy.prototype.render = function () {
context.fillStyle = 'rgba(255,255,255,'+this.transparency+')';
context.fillRect(this.x, this.y, 25, 25);
};
var main = function(speed){
var enemies = [];
for (var i = 0; i < 10; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 896;
var randomY = Math.random() * 1303;
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 === 0) {
randomX = 140;
} else {
randomX = 1281;
}
}
if (randomY > 100 && randomY < 75) {
if (randomY % 2 === 0) {
randomY = 15;
} else {
randomY = 560;
}
}
var enemy = new Enemy(randomX, randomY, 0, 0,1,speed);
enemies.push(enemy);
}
for (var i = 0; i < 15; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 200;
var randomY = Math.random() * 403;
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 === 0) {
randomX = 140;
}...