MouseOut Handle Demo
by WolfeSVK
HTML
<!DOCTYPE html>
<title>Canvas Demo</title>
<script src="script.js"></script>
<body bgcolor="#D0D0D0">
<div id="canvasContainer" align="center">
<select id="mouseBehavior">
<option value="1">Compute position by intersection of canvas edge</option>
<option value="2">Lock mouse cursor inside canvas</option>
<option value="3">Use last position inside canvas</option>
</select><br><br>
<canvas id="canvas" width="300" height="300" style="background-color: #ffffff">
Your browser doesn't support canvas object!
</canvas>
</div>
</body>
JavaScript
var canvas;
var ctx;
var mouse = [];
mouse.INTERSECTION = 1;
// compute intersection between line mouseDown - mouseUp and edge of canvas
mouse.LOCK_INSIDE = 2;
// lock mouse cursor inside
mouse.MOUSEOUT_POS = 3;
// use position where mouse left canvas
mouse.mode = mouse.INTERSECTION;
///////////////////////////////
function circle(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
}
function mouseDraggedOut(x1, y1, x2, y2, lineStyle, lineWeight) {
// x1,y1 = mouseDown; x2,y2 = mouseUp
var x3, y3, x4, y4, thisX, thisY;
if (x2 < 0) {// left edge
x3 = 0;
y3 = 0;
x4 = 0;
y4 = canvas.height;
thisX = Math.round(x1 + (((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))) * (x2 - x1));
thisY = Math.round(y1 + (((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))) * (y2 - y1));
// I must do this for other checks, else corners (when two conditions are true) couldn't be handled
// So I'll handle it one after another
x2 = thisX;
y2 = thisY;
}
if (x2 > canvas.width) {// right edge
x3 = canvas.width;
y3 = 0;
x4 = canvas.width;
y4 = canvas.height;
thisX = Math.round(x1 + (((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))) * (x2 - x1));
thisY = Math.round(y1 + (((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))) * (y2 - y1));
x2 = thisX;
y2 = thisY;
}
if (y2 < 0) {// top edge
x3 = 0;
y3 = 0;
x4 = canvas.width;
y4 = 0;
thisX = Math.round(x1 + (((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))) * (x2 - x1));
thisY = Math.round(y1 + (((x4 - x3) * (y1 - y3) - (y4 -...