JSFiddle - React, Tailwind, and code Playground
by DaveAlger
HTML
<p id="mouse-xy"></p>
<canvas id="top" class="box" x="200" y="50" width="100" height="100" c="#933" b="#faa"></canvas>
<canvas id="left" class="box" x="50" y="200" width="100" height="100" c="#993" b="#ffa"></canvas>
<canvas id="right" class="box" x="350" y="200" width="100" height="100" c="#696" b="#dfd"></canvas>
<canvas id="bottom" class="box" x="200" y="350" width="100" height="100" c="#369" b="#adf"></canvas>
<canvas id="center" class="box" x="200" y="200" width="100" height="100" c="#999" b="#ddd"></canvas>
<canvas id="top left" class="box" x="50" y="50" width="100" height="100" c="#640" b="#ca9"></canvas>
<canvas id="top right" class="box" x="350" y="50" width="100" height="100" c="#699" b="#dff"></canvas>
<canvas id="bottom left" class="box" x="50" y="350" width="100" height="100" c="#c63" b="#fda"></canvas>
<canvas id="bottom right" class="box" x="350" y="350" width="100" height="100" c="#936" b="#fad"></canvas>
CSS
.box{position: absolute;}
#mouse-xy{float:right;padding:30px;color:#999;font-family:sans-serif;}
JavaScript
var isCenterHit = false;
var checkCenterHit = true;
// draw canvas rectangles
$('.box').each(function(i) {
//alert(i);
var id = $(this).attr('id')
var w = $(this).width();
var h = $(this).height();
var c = $(this).attr('c');
var x = $(this).attr('x');
var y = $(this).attr('y');
drawRect( document.getElementById( id ).getContext('2d'), w, h, c, id );
$(this).offset({top: y, left: x});
});
function drawRect( ctx, width, height, color, text ) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = '#fff';
ctx.font = '16px sans-serif';
ctx.textBaseline = 'top';
ctx.fillText(text, 0, 0);
}
// listen for mouse over
$(document).mousemove(function(e){
var x = e.pageX;
var y = e.pageY;
var tX = $(e.target).attr('x');
var tY = $(e.target).attr('y');
var tW = $(e.target).width();
var tH = $(e.target).height();
// update mouse location
$('#mouse-xy').html("center hit: " + isCenterHit + " | X: " + x + " Y: " + y);
// rectangle coordinate hit test (this can be done other ways too)
if ( x > tX && x < tX + tW && y > tY && y < tY + tH ) {
// toggle the boolean
if ( checkCenterHit && $(e.target).attr('id') === 'center' ) {
isCenterHit = !isCenterHit;
checkCenterHit = false;
}
if ( isCenterHit ) {
// do this when center hit state is 'on'
$('body').css('background-color',$(e.target).attr('b'));
$('canvas').css('cursor','pointer');
} else {
// do this when center hit state is 'off'
$('body').css('background-color','');
$('canvas').css('cursor','');
}
}
else {
$('body').css('background-color','#ffffff');
checkCenterHit = true;
}
});