JSFiddle - React, Tailwind, and code Playground
HTML
<div class="boris">
</div>
CSS
.boris {
width:800px;
height:800px;
background-color:black;
position:relative;
}
JavaScript
var arr = [];
function enemy() {
this.name = "Boris";
this.color = "red";
this.width = "50px";
this.height = "10px";
this.x = Math.floor((Math.random() * 200) + 1);
this.y = Math.floor((Math.random() * 200) + 1);
var div = document.createElement("DIV");
div.className = "div";
this.el = div;
this.updateDOM();
}
enemy.prototype.updateDOM = function() {
var div = this.el;
div.style.backgroundColor = this.color;
div.style.position = "absolute";
div.style.left = this.x + 'px';
div.style.top = this.y + 'px';
div.style.width = this.width;
div.style.height = this.height;
};
enemy.prototype.move = function(updateDOM) {
this.x++;
var chance = Math.random();
if(chance > 0.5) {
this.y++;
}
if(updateDOM)
this.updateDOM();
}
enemy.prototype.runMoving = function(){
var self = this;
this._interval = setInterval(function() {
self.move(true);
}, 100);
}
enemy.prototype.stopMoving = function(){
if(this._interval){
clearInterval(this._interval);
this._interval = undefined;
}
}
function create() {
var one = new enemy();
document.querySelector(".boris").appendChild(one.el);
return one;
}
var alice = create();
var bob = create();
alice.runMoving();
bob.runMoving();
setTimeout(function(){
alice.stopMoving();
}, 2000)