我試着寫一個等距瓷磚的遊戲引擎,並有問題,這個代碼的速度:如何加速在畫布上繪製瓷磚?
$(function() {
var canvas = document.getElementById('GameCanvas');
var context = document.getElementById('GameCanvas').getContext('2d');
var imgObj = new Image();
imgObj.src = 'img/sand_surface.png';
var Game = {
tileScaleX: 64,
tileScaleY: 32,
FPSLimit: 50, // max allowed framerate
realFPS: 0, // real framerate
init: function() {
this.cycle(); // main animation loop
},
cycle: function() {
this.debug(); // print framerate
startTime = new Date; // start fps time
this.clear(); // celar canvas
this.draw(); // draw frame
endTime = new Date; // end fps time
setTimeout(function() {
endTimeWithSleep = new Date; // end fps time with sleep
this.realFPS = 1000/(endTimeWithSleep - startTime);
this.cycle(); // repeat animation loop
}.bind(this), (1000/this.FPSLimit) - (endTime - startTime));
},
debug: function() {
$('.DebugScreen').html('<b>FPS:</b> ' + Math.round(this.realFPS*1)/1);
},
clear: function() {
canvas.width = canvas.width; // clear canvas
},
draw: function() {
Location.drawSurface(); // draw tiles
},
}
var Location = {
width: 60,
height: 120,
drawSurface: function() {
for (y = 0; y < this.height; y++) {
for (x = 0; x < this.width; x++) {
if ((y % 2) == 0) {
rowLeftPadding = 0;
} else {
rowLeftPadding = Game.tileScaleX/2;
}
context.drawImage(imgObj, (x * Game.tileScaleX + rowLeftPadding), y * (Game.tileScaleY/2), Game.tileScaleX, Game.tileScaleY);
}
}
},
}
Game.init(); // start game
});
如果我設置Location.width和Location.height低的數字,那麼它跑得快(50個FPS),但在這個例子中(Location.width = 60
,Location.height = 120
)framerate是10fps,我需要50fps,你有什麼sugestions如何加快這個腳本?
出於好奇,乘法和除法在這裏完成了什麼:'Math.round(this.realFPS * 1)/ 1'? – 2012-01-03 15:25:19