21-为变换的图像设置动画
4.5.2 为变换的图像设置动画
为将一系列图像拼板应用到旋转的环境中,仅需在帧片断中添加循环代码,并在每个帧片段中增加frameIndex变量。例4-8就是在例4-7中添加了这些代码。
例4-8 动画和旋转
var tileSheet = new Image();
tileSheet.addEventListener('load', eventSheetLoaded , false);
tileSheet.src = "tanks_sheet.png";
var animationFrames = [1,2,3,4,5,6,7,8];
var frameIndex = 0;
var rotation = 90;
var x = 50;
var y = 50;
function eventShipLoaded(){
startUp();
}
function drawScreen(){
//绘制背景以显示出画布边缘
context.fillStyle = "#aaaaaa";
context.fillRect(0,0,500,500);
context.save();
context.setTransform(1,0,0,1,0,0)
var angleInRadians = rotation * Math.PI / 180;
context.translate(x+16, y+16)
context.rotate(angleInRadians);
var sourceX = Math.floor(animationFrames[frameIndex] % 8)*32;
var sourceY = Math.floor(animationFrames[frameIndex] / 8)*32;
context.drawImage(tileSheet, sourceX, sourceY,32,32,-16,-16,32,32);
context.restore();
frameIndex++;
if (frameIndex==animationFrames.length){
frameIndex=0;
}
}
function startUp(){
gameLoop();
}
function gameLoop() {
window.setTimeout(gameLoop, 100);
drawScreen();
}
当读者测试例4-8的时候,可以看到坦克已经旋转了90°。同时,坦克轨道在动画帧里循环。
与例4-6类似,让坦克沿着它的朝向移动。这次,它将向右移动,直到移出屏幕之外。例4-9添加了dx和dy移动矢量。注意,此时dx是1,dy是0。
例4-9 旋转并移动
var tileSheet = new Image();
tileSheet.addEventListener('load', eventSheetLoaded , false);
tileSheet.src = "tanks_sheet.png";
var animationFrames = [1,2,3,4,5,6,7,8];
var frameIndex = 0;
var rotation = 90;
var x = 50;
var y = 50;
var dx = 1;
var dy = 0;
function eventSheetLoaded(){
startUp();
}
function drawScreen(){
x = x+dx;
y = y+dy;
//绘制背景以显示出画布边缘
context.fillStyle = "#aaaaaa";
context.fillRect(0,0,500,500);
context.save();
context.setTransform(1,0,0,1,0,0)
var angleInRadians = rotation * Math.PI / 180;
context.translate(x+16, y+16)
context.rotate(angleInRadians);
var sourceX=Math.floor(animationFrames[frameIndex] % 8)*32;
var sourceY=Math.floor(animationFrames[frameIndex] / 8)*32;
context.drawImage(tileSheet, sourceX, sourceY,32,32,−16,−16,32,32);
context.restore();
frameIndex++;
if (frameIndex ==animationFrames.length){
frameIndex=0;
}
}
function startUp(){
gameLoop();
}
function gameLoop() {
window.setTimeout(gameLoop, 100);
drawScreen();
}
当例4-9运行时,读者会看到坦克缓缓地穿过屏幕移向右侧,可以看到它的轨迹在简单的灰色背景上沿着拼图上的拼板活动起来。
至此,本章使用拼板模拟了基于素材的动画移动。下节将尝试如何使用图像拼图来创建多个拼板组成的复杂背景。