JSFiddle - React, Tailwind, and code Playground
HTML
<div id="canvasContainer">
<canvas width="300" height="300" id="surface"></canvas>
<div id="selectionRect">
<span id="select"></span>
</div>
<div class="selectionOutline">
<span></span>
</div>
</div>
CSS
body{margin:0;padding:0;}
div,canvas
{
box-sizing:border-box;
}
#canvasContainer
{
display:inline-block;
margin:0;
padding:0;
}
#selectionRect
{
display:none;
position:absolute !important;
z-index : 9000 !important;
cursor:default !important;
}
#surface
{
display:block;
}
#select
{
width:100%;
height:100%;
float:left;
background:rgba(0,76,198,.4);
}
.active
{
display:block !important;
}
.selectionOutline
{
position:absolute;
display:none;
}
.selectionOutline > span
{
width:100%;
height:100%;
float:left;
background:transparent;
border : 1px dashed #888;
}
JavaScript
function Rect(x,y,width,height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
var selection;
$(document).ready(function(){
var lastX,lastY;
$("#canvasContainer").on('mousedown',function(e){
var x = e.clientX;
var y = e.clientY;
$("#selectionOutline").remove();
var canvas = document.querySelector('#surface');
if((x >= 0 && x <= canvas.width) && (y >= 0 && y <= canvas.height) )
{
$("#selectionRect").addClass("active");
$("#selectionRect").css({
top : y,
left:x
});
lastX = x;
lastY = y;
$(document).bind('mousemove',size);
$(document).bind('mouseup',select);
}
});
function size(e)
{
var x = e.pageX;
var y = e.pageY;
var mWidth = $('#surface').width();
var mHeight = $("#surface").height();
if(x <= 0)
{
x=0;
}
else if(x >= mWidth)
{
x = mWidth;
}
if(y <= 0)
{
y=0;
}
else if(y >= mHeight)
{
y = mHeight;
}
if (e.pageX <= lastX && e.pageY >= lastY) {
$("#selectionRect").css({
'left': x
});
} else if (e.pageY <= lastY && e.pageX >= lastX) {
$("#selectionRect").css({
'top': y
});
} else if (e.pageY < lastY && e.pageX < lastX) {
$("#selectionRect").css({
'left': x,
"top": y
});
}
var width = Math.abs(x - lastX);
var height = Math.abs(y - lastY);
$('#selectionRect').css({
width : width,
height:height
});
}
function select(e)
{
$(document).unbind('mousemove',size);
$(document).unbind('mouseup',select);
var px = /\d+/;
var selection = new Rect(Number($('#selectionRect').css("left").match(px)),
Number($('#selectionRect').css("top").match(px)),
$('#selectionRect').width(),
$('#selectionRect').height());
...