Skip to content

Instantly share code, notes, and snippets.

@hit1205
Last active August 27, 2016 13:53
Show Gist options
  • Save hit1205/5f811e70aa7bb900089e2898fc203224 to your computer and use it in GitHub Desktop.
Save hit1205/5f811e70aa7bb900089e2898fc203224 to your computer and use it in GitHub Desktop.
偵測滑鼠游標是否繞圈圈。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var lastMouseX = null,
lastMouseY = null,
lastMouseDeltaX = null,
lastMouseDeltaY = null,
minMouseDelta = 80, // 游標最小需移動距離
mouseMoveLog = [],
clockMap = {
'1234': 1,
'2341': 1,
'3412': 1,
'4123': 1,
'4321': -1,
'3214': -1,
'2143': -1,
'1432': -1
};
$(document).on('mousemove', function(e) {
var curX = e.pageX,
curY = e.pageY,
deltaX = curX - lastMouseX,
deltaY = curY - lastMouseY,
delta = Math.round(Math.sqrt(Math.pow(deltaY, 2) + Math.pow(deltaX, 2))),
curArrow = 0;
if(delta >= minMouseDelta) {
if(lastMouseDeltaY < 0 && deltaY > 0) {
curArrow = 1;
}
else if(lastMouseDeltaX > 0 && deltaX < 0) {
curArrow = 2;
}
else if(lastMouseDeltaY > 0 && deltaY < 0) {
curArrow = 3;
}
else if(lastMouseDeltaX < 0 && deltaX > 0) {
curArrow = 4;
}
if(curArrow != 0) {
if(mouseMoveLog.length > 0) {
var absArrowDiff = Math.abs(mouseMoveLog[mouseMoveLog.length - 1] - curArrow);
if(absArrowDiff == 0) {
mouseMoveLog.pop();
}
else if(absArrowDiff == 2) {
mouseMoveLog = [];
}
}
mouseMoveLog.push(curArrow);
if(mouseMoveLog.length >= 4) {
detectCircle();
}
}
lastMouseX = curX;
lastMouseY = curY;
lastMouseDeltaX = deltaX;
lastMouseDeltaY = deltaY;
}
});
function detectCircle() {
var curDirection = 0,
arrowKey = mouseMoveLog.join('').substr(-4),
mostMatchedKey = '',
curTimestamp = new Date().getTime();
$.each(clockMap, function(k, v) {
if(k == arrowKey) {
mostMatchedKey = k;
return false;
}
if(mostMatchedKey.length < 3 && k.substr(0, 3) == arrowKey.substr(-3)) {
mostMatchedKey = k.substr(0, 3);
}
else if(mostMatchedKey.length < 2 && k.substr(0, 2) == arrowKey.substr(-2)) {
mostMatchedKey = k.substr(0, 2);
}
else if(mostMatchedKey.length < 1 && k.substr(0, 1) == arrowKey.substr(-1)) {
mostMatchedKey = k.substr(0, 1);
}
});
switch(mostMatchedKey.length) {
case 4:
mouseMoveLog = [];
curDirection = clockMap[mostMatchedKey];
break;
default:
mouseMoveLog = mostMatchedKey.split('');
}
switch(curDirection) {
case 1:
// 順時針
$('body').prepend(curTimestamp + ': cw<br />');
console.log('cw');
break;
case -1:
// 逆時針
$('body').prepend(curTimestamp + ': ccw<br />');
console.log('ccw');
break;
default:
// 未知
$('body').prepend(curTimestamp + ': unknown<br />');
console.log('unknown');
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment