JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<h4>Click on the person icon.</h4>
<div id="wrapper">
    <canvas id="canvas" width=300 height=300></canvas>
    <div id="myname">
        <input type="text" id="name" size=15>
        <button id="submitName">OK</button>
    </div>
</div>

CSS

body {
    background-color: ivory;
}
#wrapper {
    position:relative;
}
#canvas {
    position:absolute;
    border:1px solid red;
}
#myname {
    position:absolute;
    left:28px;
    top:3px;
    visibility:hidden;
}

JavaScript

// canvas related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;


// name input related variables
$myname = $("#myname");
var playerName = "";

// load a person icon and display it top-left
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/personIcon.png";

function start() {
    ctx.drawImage(img, 0, 0);
}


// listen for mousedown events
function handleMouseDown(e) {

    // tell the browser we'll handle this event
    e.preventDefault();
    e.stopPropagation();

    // get the mouse position
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // if the mouse was pressed over the person icon
    // then make the name-input visible
    if (mouseX < img.width && mouseY < img.height) {
        $("#name").text(playerName);
        $myname.css("visibility", "visible");
    }

}

// listen for mousedown events
$("#canvas").mousedown(function (e) {
    handleMouseDown(e);
});

// listen for clicks on the OK button
// if clicked, save the player's name
// and hide the name-input
$("#submitName").click(function () {
    playerName = $("#name").val();
    $myname.css("visibility", "hidden");
    alert("The players name is "+playerName);
});