JSFiddle - React, Tailwind, and code Playground
HTML
<p>Drag the corners to resize</p>
<canvas id="canvas" width=500 height=500></canvas>
JavaScript
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false,
mouseX,
mouseY,
closeEnough = 10,
dragTL = dragBL = dragTR = dragBR = false;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
rect = {
startX: 100,
startY: 200,
w: 300,
h: 200
}
}
function mouseDown(e) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
// if there isn't a rect yet
if (rect.w === undefined) {
rect.startX = mouseY;
rect.startY = mouseX;
dragBR = true;
}
// if there is, check which corner
// (if any) was clicked
//
// 4 cases:
// 1. top left
else if (checkCloseEnough(mouseX, rect.startX) && checkCloseEnough(mouseY, rect.startY)) {
dragTL = true;
}
// 2. top right
else if (checkCloseEnough(mouseX, rect.startX + rect.w) && checkCloseEnough(mouseY, rect.startY)) {
dragTR = true;
}
// 3. bottom left
else if (checkCloseEnough(mouseX, rect.startX) && checkCloseEnough(mouseY, rect.startY + rect.h)) {
dragBL = true;
}
// 4. bottom right
else if (checkCloseEnough(mouseX, rect.startX + rect.w) && checkCloseEnough(mouseY, rect.startY + rect.h)) {
dragBR = true;
}
// (5.) none of them
else {
// handle not resizing
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}
function checkCloseEnough(p1, p2) {
return Math.abs(p1 - p2) < closeEnough;
}
function mouseUp() {
dragTL = dragTR = dragBL = dragBR =...