用 jQuery 也能做出類似 Flash 逐幀動畫的效果。這個擲骰子小遊戲的原理是:點擊後讓骰子在幾個位置之間跳動,同時快速切換背景圖上的不同「幀」(各點數與運動模糊過渡圖),最後停在隨機產生的點數上並顯示結果。
先準備素材:把 1~6 點的骰子圖,以及中間過渡用的模糊圖(模擬運動殘影)拼在同一張 dice.png 上,作為骰子的背景圖(sprite)。接著載入 jQuery:
<script type="text/javascript" src="js/jquery.js"></script>
在 body 中放上行與提示文字,#dice 用來置放骰子,#result 顯示結果:
<div id="dice" class="dice dice_1"></div> <p id="result">請直接點擊上面的骰子!</p>
.wrap { width: 90px; height: 90px; margin: 120px auto 30px auto; position: relative; }
.dice { width: 90px; height: 90px; background: url(dice.png) no-repeat; }
.dice_1 { background-position: -5px -4px; }
.dice_2 { background-position: -5px -107px; }
.dice_3 { background-position: -5px -212px; }
.dice_4 { background-position: -5px -317px; }
.dice_5 { background-position: -5px -427px; }
.dice_6 { background-position: -5px -535px; }
/* 三張過渡幀(模糊處理) */
.dice_t { background-position: -5px -651px; }
.dice_s { background-position: -5px -763px; }
.dice_e { background-position: -5px -876px; }
p#result { text-align: center; font-size: 16px; }
p#result span { font-weight: bold; color: #f30; margin: 6px; }
/* 透明遮罩,用來防止動畫期間重複點擊 */
#dice_mask {
width: 90px; height: 90px;
background: #fff; opacity: 0;
position: absolute; top: 0; left: 0;
z-index: 999;
}
過渡圖我用簡單的模糊處理做出來,你也可以改用 CSS3 的 filter: blur() 來達成同樣效果。
$(function(){
var dice = $("#dice");
dice.click(function(){
dice.attr("class", "dice"); // 清除上次動畫後的點數
dice.css("cursor", "default");
$(".wrap").append("<div id='dice_mask'></div>"); // 加遮罩
var num = Math.floor(Math.random() * 6 + 1); // 隨機 1~6
dice.animate({ left: '+2px' }, 100, function(){
dice.addClass("dice_t");
})
.delay(200)
.animate({ top: '-2px' }, 100, function(){
dice.removeClass("dice_t").addClass("dice_s");
})
.delay(200)
.animate({ opacity: 'show' }, 600, function(){
dice.removeClass("dice_s").addClass("dice_e");
})
.delay(100)
.animate({ left: '-2px', top: '2px' }, 100, function(){
dice.removeClass("dice_e").addClass("dice_" + num); // 停在最終點數
$("#result").html("您擲得點數是<span>" + num + "</span>");
dice.css('cursor', 'pointer');
$("#dice_mask").remove(); // 移除遮罩,可再次點擊
});
});
});
直覺上會想用 one()、live()、bind() 或 on() 來避免連點,但這些方法在動畫情境下都不合適——它們管的是事件綁定,而不是「動畫進行中禁止互動」。我採用的辦法是:動畫開始時蓋上一層與骰子同尺寸的透明遮罩,動畫結束後再移除。簡單、直觀,也不干擾既有的事件綁定。
另一個常見做法是加一個狀態旗標:
var rolling = false;
dice.click(function(){
if(rolling) return; // 動畫進行中直接忽略點擊
rolling = true;
// ... 動畫
// 在最後一個回呼中:rolling = false;
});
這個效果本質上就是模擬 Flash 的時間軸逐幀播放,用 jQuery 就能勝任,雖然華麗度不如 Flash,但勝在免插件、易於整合。本文的擲骰子是為下一篇做鋪墊——接下來會示範結合 jQuery、HTML、CSS、PHP 與 MySQL 的擲骰子抽獎遊戲,可以控制擲出各點數的機率,同樣是個有趣的小專案。