Last active
June 29, 2017 14:10
-
-
Save gujc71/ae32ff529de3bbbb9f86227193c233ec to your computer and use it in GitHub Desktop.
Mouse Control Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
<title>Mouse Control Example</title> | |
<style> | |
.selector { | |
position: absolute; | |
border: 1px dotted ; | |
} | |
.rectangle{ | |
position: absolute; | |
border: 1px solid; | |
} | |
</style> | |
<script> | |
// make shape | |
var selector = null; | |
var sPos = null; | |
window.onload = function() { | |
selector = document.getElementsByClassName("selector")[0]; | |
selector.style.display = "none"; | |
document.onselectstart = function() { return false } | |
document.onmousedown = mousedown; | |
document.onmousemove = mousemove; | |
document.onmouseup = mouseup; | |
} | |
function mousedown(ev){ | |
sPos = {x: ev.pageX, y: ev.pageY}; | |
setPosition(selector, {x1: ev.pageX, y1: ev.pageY, x2: 0, y2: 0}); | |
selector.style.display = ""; | |
} | |
function mousemove(ev){ | |
if (sPos === null) { return;} | |
setPosition(selector, calcPosition(sPos, {x2: ev.pageX, y2: ev.pageY})); | |
} | |
function mouseup(ev){ | |
var rt = calcPosition(sPos, {x2: ev.pageX, y2: ev.pageY}); | |
setPosition(selector, rt); | |
selector.style.display = "none"; | |
sPos = null; | |
var node = document.createElement("div"); | |
document.body.appendChild(node); | |
node.className = "rectangle"; | |
setPosition(node, rt); | |
} | |
function calcPosition(pos, size){ | |
return {x1: Math.min(pos.x, size.x2), y1: Math.min(pos.y, size.y2), | |
x2: Math.abs(size.x2-sPos.x), y2: Math.abs(size.y2-sPos.y)}; | |
} | |
function setPosition(obj, rt){ | |
obj.style.left = rt.x1 + "px"; | |
obj.style.top = rt.y1 + "px"; | |
obj.style.width = rt.x2 + "px"; | |
obj.style.height = rt.y2 + "px"; | |
} | |
</script> | |
</head> | |
<body> | |
<div class="selector" style="left: 100px; top: 100px;"> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment