讀取 sprite sheet 並產生動畫,介紹兩種方法: css animation 與 canvas
這裡示範使用的 sprite sheet,是使用六角學院的第二屆精神時光屋,使用 Janet Yang 設計師的原始圖檔,若有侵權,再麻煩告知
使用 css animation 的 steps
首先要了解 steps 的特性
steps() 語法為
steps(number, position)
number: 表示把動畫分了多少段落
position: 表示時間是從開頭連續,還是結尾連續。使用 start、end 兩個關鍵字
記住 postion 重點: 一切都是反的! start不是開始,而是結束;end不是結束,而是開始。
好吧,其實 demo 用到的只用到 steps number XD
把 steps 分成 10 段 "一步一步" 呈現
html:
<div class="hedgehog"></div>
css:
.hedgehog {
width: 268px;
height: 351px;
background-image: url("https://i.imgur.com/JKPX5Zs.png");
animation: play 4s steps(10) infinite;
}
@keyframes play {
from { background-position: 0px; }
to { background-position: -2692px; }
}
即可得到刺蝟完整動畫(有跳躍)
demo
html:
<canvas id="hedgehog"></canvas>
js:
(function() {
var hedgehog, hedgehogImage, canvas;
function gameLoop() {
window.requestAnimationFrame(gameLoop);
hedgehog.update();
hedgehog.render();
}
function sprite(options) {
var that = {},
frameIndex = 0,
tickCount = 0,
ticksPerFrame = options.ticksPerFrame || 0,
numberOfFrames = options.numberOfFrames || 1;
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.update = function() {
tickCount += 1;
if (tickCount > ticksPerFrame) {
tickCount = 0;
// If the current frame index is in range
if (frameIndex < numberOfFrames - 1) {
// Go to the next frame
frameIndex += 1;
} else {
frameIndex = 0;
}
}
};
that.render = function() {
// Clear the canvas
that.context.clearRect(0, 0, that.width, that.height);
// Draw the animation
that.context.drawImage(
that.image,
(frameIndex * that.width) / numberOfFrames,
0,
that.width / numberOfFrames,
that.height,
0,
0,
that.width / numberOfFrames,
that.height
);
};
return that;
}
// Get canvas
canvas = document.getElementById("hedgehog");
canvas.width = 269;
canvas.height = 351;
// Create sprite sheet
hedgehogImage = new Image();
// Create sprite
hedgehog = sprite({
context: canvas.getContext("2d"),
width: 1615,
height: 351,
image: hedgehogImage,
numberOfFrames: 6,
ticksPerFrame: 10
});
// Load sprite sheet
hedgehogImage.addEventListener("load", gameLoop);
hedgehogImage.src = "https://i.imgur.com/JKPX5Zs.png";
})();
即可得到刺蝟的行走(沒有跳躍)
至於要控制物件移動,等事件控制單元再介紹,因為快子夜啦!!!
若有錯誤的觀念或是資料授權有問題,再煩請通知我,謝謝