Draw Selection Rect
by profesor08
CSS
body {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
JavaScript
let canvas = document.createElement("canvas")
let ctx = canvas.getContext("2d")
document.body.appendChild(canvas);
let x1 = 0, y1 = 0, x2 = 0, y2 = 0;
let canDrawSelection = false;
canvas.addEventListener("mousedown", function(e) {
canDrawSelection = true;
x1 = e.clientX;
y1 = e.clientY;
x2 = e.clientX;
y2 = e.clientY;
});
canvas.addEventListener("mouseup", function(e) {
canDrawSelection = false;
});
canvas.addEventListener("mousemove", function(e) {
x2 = e.clientX;
y2 = e.clientY;
});
function drawSelection() {
if (canDrawSelection === true) {
ctx.beginPath();
ctx.lineWidth="2";
ctx.strokeStyle="white";
ctx.rect(x1, y1, x2 - x1, y2 - y1);
ctx.stroke();
}
}
function render() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
ctx.fillStyle = "#2B2E35";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
drawSelection();
}
function animate() {
requestAnimationFrame(animate);
render();
}
animate();