17-绘制拼板
4.4.5 绘制拼板
使用drawImage()函数在每个循环里将新的拼板放到屏幕上。
context.drawImage(tileSheet, sourceX, sourceY,32,32,50,50,32,32);
在此,将计算过的sourceX值和sourceY值传送给drawImage()函数,也就是以宽32、高32和坐标(50,50)为参数在画布上绘制图像。完整代码如例4-5所示。
例4-5 高级素材动画
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;function eventSheetLoaded(){
startUp();
}
function drawScreen(){
//绘制背景以显示出画布边缘
context.fillStyle = "#aaaaaa";
context.fillRect(0,0,500,500);
var sourceX = Math.floor(animationFrames[frameIndex] % 8)*32;
var sourceY = Math.floor(animationFrames[frameIndex] / 8)*32;
context.drawImage(tileSheet, sourceX, sourceY,32,32,50,50,32,32);
frameIndex++;
if (frameIndex ==animationFrames.length){
frameIndex=0;
}
}
function startUp(){
gameLoop();
}
function gameLoop() {
window.setTimeout(gameLoop, 100);
drawScreen();
}
当运行这个示例的时候,读者将看到8个坦克拼板帧按顺序地移动并且重复进行——唯一的问题是这个坦克并不能走到别处。随后就会解决这个小问题,让坦克能够在整个屏幕上行驶。