l'essentiel est invisible pour les yeux

Saturday, December 08, 2007

[Javascript] iPhone / iPod touchの「slide to unlock」のエフェクト(Effect.Illuminate)を実装

iPhone / iPod touchのTOPに表示されている'slide to unlock'のエフェクトです。

Effect.illuminate




Usage

Effect.Illuminate('illuminated_msg');


Option

Effect.Illuminate('illminated_msg', {color: '#fff', repeat: true});

color: スポットライトの色です。
repeat: エフェクトを繰り返すかどうか。
size: スポットライトのサイズ(文字数)

Source code
テキストノード以外は、子ノードに対して再起的にエフェクトを適用し、テキストノードの場合は、スポットライトを照らす関数を遅延呼び出しで実行する。同時にオプションで指定した文字数以上照らした場合は、スポットライトを消す(移動)するエフェクトを開始する。エフェクトを実行し終えたら、innerHTMLの内容を元の状態に復帰する。


var Effect = Effect || {};
Effect.Illuminate = function(element, options) {
var effect = arguments.callee;
element = $(element);
if(element.tagName) {
// Save the original style
with(effect) {
color = element.getStyle('color');
innerHTML = element.innerHTML;
}
$A(element.childNodes).each(function(node) {effect(node, options)});
return;
}

// It's only executed when node is a text node.
options = new Hash({
color: '#ffffff',
size: 4,
repeat: true,
interval: 70
}).merge(options);

// The all characters is replaced because accessing an innerHTML property is pretty slow.
var parent = element.parentNode;
parent.innerHTML = $A(element.nodeValue).map(function(text) {
return ['<span style="color: ', this.color, '">', text, '</span>'].join('');
}).join('');

var self = this, started = false;
var turnOn = function(node) {node.style.color = options.color};
var turnOff = function(node) {node.style.color = self.color};
var restore = function() {parent.innerHTML = self.innerHTML};
var startTurnOffEffect = function(callback) {
started = true;
$A(parent.childNodes).inject(0, function(delay, node, idx) {
with({idx: idx}) {
setTimeout(function() {
turnOff(node);
if(callback['onEnd'] && idx == parent.childNodes.length - 1) callback['onEnd']();
}, delay);
}
return delay + options.interval;
});
};
// Start the effect
$A(parent.childNodes).inject(0, function(delay, node, idx) {
setTimeout(function() {
turnOn(node);
if(!started && idx > options.size) {
startTurnOffEffect({onEnd: function() {
restore();
if(options.repeat) effect(parent, options);
}});
}
}, delay);
return delay + options.interval;
});
};



iPhone or iPod touchユーザなら一目瞭然ですが、iPhone / iPod touchのエフェクトはより滑らか。またの機会に、イルミネーションをより滑らか(2〜3ステップで明るくなるよう)にするかもしれません。