I have some functions to draw rectangles on a canvas element. When the element is drawn, I want to be able to resize it by dragging its corners.
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();
<canvas id="canvas" width="500" height="500"></canvas>
Make sure to use some kind of threshold value to check for dragging on corners, use a
closeEnough
variable to hold this threshold then check corners by seeing if the absolute value of the difference between corner point and mouse point is less than the threshold. Apart from that, it is just a lot of cases to go through. Here is a jsFiddle of itDo a handle system: when the mouse move, get the distance to each corner to get the first one that is near the cursor then save it and resize your rectangle according to it.
Here is a JSfiddle illustrating it: http://jsfiddle.net/BaliBalo/9HXMG/