Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Created April 15, 2011 13:14
Show Gist options
  • Save mumoshu/921667 to your computer and use it in GitHub Desktop.
Save mumoshu/921667 to your computer and use it in GitHub Desktop.
PCの傾き具合によりページをスクロールするGreasemonkeyスクリプト。MacBookやThinkPadで動くと思います。
// ==UserScript==
// @name Scroll by orientation
// @namespace jp.mumoshu.scroll_by_orientation
// @include *
// ==/UserScript==
(function() {
/**
* 傾きの絶対値(0から1.0)がこの値より大きいときにスクロールをはじめる
*/
var ORIENTATION_THRESHOLD = 0.1;
/**
* 加速度の倍率。加速度は傾き(-1.0 ~ +1.0) * 倍率 px/sec^2
*/
var ACCELERATION_BIAS = 20;
/**
* 速度の減衰率を表す。1.0近いほど減衰しない(端末を水平にしてもずっとスクロールしつづける)
* 逆に0.0に近いほど、端末を水平にしたとき時間経過に伴いスクロールが止まる。
*/
var VELOCITY_DECAY = 0.0;
function vectorLength(x, y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
/**
* 2次元ベクトル。わざわざクラスにしない方が高速なんですけどね。。
* @param x
* @param y
*/
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
Vector2D.prototype.multiplyBy = function(number) {
this.x *= number;
this.y *= number;
};
Vector2D.prototype.add = function(vector) {
this.x += vector.x;
this.y += vector.y;
};
Vector2D.prototype.len = function() {
return vectorLength(this.x, this.y);
};
/**
* 再利用しないのでただのオブジェクトにしておきますね
*/
var state = {
orientationx: 0,
orientationY: 0,
acceleration: new Vector2D(0, 0),
velocity: new Vector2D(0, 0),
handleOrientation: function(orientation) {
var ox = orientation.x;
var oy = orientation.y;
ox = Math.abs(ox) < ORIENTATION_THRESHOLD ? 0.0 : ox;
oy = Math.abs(oy) < ORIENTATION_THRESHOLD ? 0.0 : oy;
this.velocity.multiplyBy(VELOCITY_DECAY);
this.acceleration.x = ox * ACCELERATION_BIAS;
this.acceleration.y = oy * ACCELERATION_BIAS;
this.velocity.add(this.acceleration);
}
};
setInterval(function() {
window.scrollBy(state.velocity.x, state.velocity.y);
}, 16);
window.addEventListener("MozOrientation", function(orientation) { state.handleOrientation(orientation); }, true);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment