JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
</head>
<body>
<canvas id="canvas" widht="500" height="200"></canvas>
<div id="text"></div>
</body>
</html>
CSS
#canvas {
border: 1px solid black;
}
JavaScript
var text = document.getElementById("text");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width = 500;
var height = canvas.height = 200;
var stop = false;
// класс объекта ЕДА
class Food {
constructor(ctx, type = "food", canvas) {
this.ctx = ctx;
this.randomWarp();
this.display = false;
this.warpTime = Math.floor(10 + Math.random() * 10);
this.count = 0;
this.type = type;
if (type === "mouse") {
let listener = (e) => {
this.x = e.pageX - e.target.offsetLeft;
this.y = e.pageY - e.target.offsetTop;
}
canvas.addEventListener('mousemove', listener);
canvas.addEventListener('touchmove', listener);
}
if (type === "blackhole") {
this.display = true;
}
}
loop() {
if (this.type != "food") return;
this.count++;
if (this.count >= this.warpTime) {
this.count = 0;
this.randomWarp();
}
}
// метод телепортирует еду в новые случайные координаты
randomWarp() {
this.x = 20 + Math.floor(Math.random() * (width - 40));
this.y = 20 + Math.floor(Math.random() * (height - 40));
}
// метод рисует еду
draw() {
if (!this.display) return;
// this.ctx.fillRect(food.x-5,food.y-5,10,10);
this.ctx.fillStyle = "black";
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, 40, 0, Math.PI * 2);
this.ctx.fill();
}
}
// класс объекта СУЩЕСТВО
class Entity {
constructor(ctx, type = "passive") {
this.ctx = ctx;
this.type = type;
this.rubbing = 0.97;
this.targets = [];
this.randomWarp();
let brightnes = Math.floor(128 * (this.speed - 0.05) / 0.65);
this.color = "black";
/* this.color = "rgb(0,"+(32+brightnes)+",0)" */
;
if (this.type === "active") {
this.color = "rgba(" + (64 + brightnes) + ",0,0, 0.9)";
} else if (this.type === "passive") {
this.color = "rgba(" + (128 - brightnes) + ",0,0, 0.9)";
}
}
loop()...