JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<br/><p>Click once to select a box</p>
<p>The selected box will be highlighted RED
<p>Click a second box to swap the boxes</p>
<canvas id="canvas" width=400 height=300></canvas>
CSS
body{ background-color: ivory; }
canvas{border:1px solid red;}
JavaScript
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var canvasWidth=canvas.width;
var canvasHeight=canvas.height;
// create "pieces"
var selectedPiece=-1;
var pieceSize=75;
var pieces=[];
pieces.push({x:50,y:30,color:"orange"});
pieces.push({x:150,y:30,color:"green"});
pieces.push({x:250,y:30,color:"blue"});
for(var x=0;x<pieces.length;x++){
drawPiece(x,false);
}
// draw the specified piece
// stroke it in red if it's selected
function drawPiece(pieceId,isStroked){
if(pieceId<0){return;}
var piece=pieces[pieceId];
ctx.save();
ctx.beginPath();
ctx.fillStyle=piece.color;
ctx.rect(piece.x,piece.y,pieceSize,pieceSize);
ctx.fill();
ctx.strokeStyle=(isStroked ? "red" : "black");
ctx.lineWidth=6;
ctx.stroke();
ctx.fillStyle="white";
ctx.font = 'italic 18px Calibri';
ctx.fillText("Box#"+pieceId,piece.x+15,piece.y+25);
ctx.restore();
}
function hitTest(x,y){
var hit=-1;
for(var pieceId=0;pieceId<pieces.length;pieceId++){
piece=pieces[pieceId];
var isHit=!(x<piece.x || x>(piece.x + pieceSize) || y<piece.y || y>(piece.y + pieceSize));
if(isHit){
hit=pieceId;
break; // Hit! We're outta here...
}
}
return(hit); // returns piece# if hit else -1 to indicate no hits
}
function handleMouseUp(e){
canMouseX=parseInt(e.clientX-offsetX);
canMouseY=parseInt(e.clientY-offsetY);
// de-highlight previous selection, if any
...