JSFiddle - React, Tailwind, and code Playground

by danya_postfactum

HTML

<div class="bug"></div>

CSS

.bug{
    display: inline-block;
    width: 30px;
    height: 40px;
    background: red;
    position: absolute;
    transition-property: transform top left;
    transition-duration: 0.4s;
}
.bug:before, .bug:after{
    content: '•';
    color: #fff;
    position: absolute;
}
.bug:before{
    left: 5px;
}
.bug:after{
    right: 5px;
}

JavaScript

function Bug() {
    this.step = 5;
    this.rotation = 0;
    this.direction = 'top';
    this.top = 0;
    this.left = 0;
    this.element = document.querySelector('.bug');
    this.bindKeys();
    debugger;
}
 
Bug.prototype.moveTo = function(direction) {
    this.direction = direction;
    var angle = {top: 0, left: 270, right: 90, bottom: 180}[direction];
    var diff = angle - (this.rotation % 360);
    console.log(this.rotation, diff, (diff - 360));
    if (diff > 180 )
        diff = diff - 360;
    else if (diff < -180 )
        diff = diff + 360;
    
    this.rotation += diff;

    if (diff == 0) {
        // продвигаемся
        this.advance();
    }
    this.update();
};
    
Bug.prototype.advance = function() {
    switch (this.direction) {
        case 'top':
            this.top -= this.step;
            break;
        case 'bottom':
            this.top += this.step;
            break;
        case 'left':
            this.left -= this.step;
            break;
        case 'right':
            this.left += this.step;
            break;
    }
};

Bug.prototype.update = function() {
    var style = this.element.style;
    style.top = this.top + 'px';
    style.left = this.left + 'px';
    style.transform = 'rotate(' + this.rotation + 'deg)';
};
 
Bug.prototype.bindKeys = function(e) {
    var keyNav = {38: 'top', 39: 'right', 37: 'left', 40: 'bottom'};
    var bug = this;
    document.addEventListener('keydown', function(e) {
        if (e.keyCode in keyNav)
            bug.moveTo(keyNav[e.keyCode]);
    }, false);
};
 
 
var bug = new Bug();
 
bug.moveTo('top');