JSFiddle - React, Tailwind, and code Playground
HTML
<div id="selection"></div>
CSS
#selection {
display: none;
position: absolute;
background: lightblue;
border-color: blue;
border-width: 1px;
border-style: solid;
opacity: .5;
}
* {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: default;
}
JavaScript
(function() {
var beginX, beginY; // a posição do vértice fixo
var active; // se a seleção está ativa (visível)
var selection = document.getElementById("selection"); // o elemento
window.onmousedown = function (e) {
beginX = e.clientX;
beginY = e.clientY;
active = true;
selection.style.display = "block"; // deixar a div visível
window.onmousemove(e); // forçar a atualização de posição (função abaixo)
};
window.onmousemove = function (e) {
if (active) {
// cx,cy = a posição do segundo vértice
var cx = e.clientX;
var cy = e.clientY;
// x,y,w,h = o retângulo entre os vértices
var x = Math.min(beginX, cx);
var y = Math.min(beginY, cy);
var w = Math.abs(beginX - cx);
var h = Math.abs(beginY - cy);
// aplicar a posição e o tamanho
selection.style.left = x+"px";
selection.style.top = y+"px";
selection.style.width = w+"px";
selection.style.height = h+"px";
}
};
window.onmouseup = function (e) {
active = false; // desligar
selection.style.display = "none"; // e ocultar
};
})();