JSFiddle - React, Tailwind, and code Playground

by JThomas

HTML

<canvas width="500" height="250"></canvas>

CSS

canvas {
    border: 2px solid #000;
}

JavaScript

var canvas = document.querySelector("canvas"),
    ctx = canvas.getContext('2d');

var entity = function (x, y, spriteSize, spriteFile) {
    this.x = x;
    this.y = y;
    this.spriteSize = spriteSize;
    this.spriteFile = spriteFile;

    function draw() {}

    function update(ctx) {}
}

var player = function (x, y, spriteSize, spriteFile) {
    entity.call(this, x, y, spriteSize, spriteFile);

    //Can be 'rest', 'extending', 'retracting'
    this.tongueState = 'rest';
    this.tongueSpeed = 0.1;
    this.currentTongueFrame = 0;
    this.tongueTarget = {};
};

player.prototype = new entity;

player.prototype.draw = function (ctx) {
    //draw frog at x,y
    
    if (this.tongueState == 'extending') {
        var tx = this.x + (this.tongueTarget.x - this.x) * this.currentTongueFrame,
            ty = this.y + (this.tongueTarget.y - this.y) * this.currentTongueFrame;
        
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        ctx.lineTo(tx, ty);
        ctx.stroke();
    }
}

player.prototype.update = function () {
    if (this.tongueState == 'extending') {
        this.currentTongueFrame += this.tongueSpeed;
        
        if (this.currentTongueFrame > 1) this.currentTongueFrame = 0;
    }
};
//call back for a canvas click to extend the tongue to that coords
player.prototype.extendTongue = function(x, y){
        this.tongueTarget = { x: x, y:y };
        this.tongueState = 'extending';
        console.log(this.tongueState);
    };

var p = new player(canvas.width / 2, canvas.height, {
    width: 32,
    height: 32
}, {});

canvas.addEventListener("click", function(e){
    p.extendTongue(e.offsetX, e.offsetY);
});

var fly = function(){};
fly.prototype = new entity;
fly.prototype.draw = function(){};
console.log(new fly);

function loop() {
    p.update();
    p.draw(ctx);
}

setInterval(loop, 1000 / 30);
console.log(p);