我使用Raphaël.js创建了我的第一个SVG游戏。 .
在 Chrome 中,游戏感觉很快,但在 IE(可以理解,因为它使用 VML)、Firefox、iPad safari 等其他浏览器中,有时感觉很慢。
我正在寻找一些关于如何优化代码以发挥绝对最佳性能的技巧。我已经尽力自己优化它,但我只是一个 JS 初学者。另外,请随意提及是否应该使用我未使用的任何推荐的最佳实践。瓶颈可能在哪里?
您可以在jsfiddle上查看代码并尝试游戏。 .
最佳答案
减少方法调用
var left1 = a.attr('x'),
left2 = b.attr('x'),
right1 = a.attr('x') + a.attr('width'),
right2 = b.attr('x') + b.attr('width'),
top1 = a.attr('y'),
top2 = b.attr('y'),
bottom1 = a.attr('y') + a.attr('height'),
bottom2 = b.attr('y') + b.attr('height');
可以像这样优化:
var left1 = a.attr('x'),
left2 = b.attr('x'),
right1 = left1 + a.attr('width'),
right2 = left2 + b.attr('width'),
top1 = a.attr('y'),
top2 = b.attr('y'),
bottom1 = top1 + a.attr('height'),
bottom2 = top2 + b.attr('height');
这可以为每个 hitDetection
节省 4 次方法调用称呼。同样适用于wallDetection
可能还有其他功能。事实上,我还相信您可以删除宽度和高度调用,并通过闭包进行缓存,因为它们在创建后非常静态,请参阅下一个示例。
还有下一点:
var animateEnemies = function(enemy) {
var enemyWidth = enemy.attr('width'),
enemyHeight = enemy.attr('height'),
...
你设置了敌人的宽度和高度一次,所以它们看起来相当恒定,你可以删除 .attr()
从 createEnemies
查找并传递宽度和高度也可以打电话。
var animateEnemies = function(enemy , enemyWidth , enemyHeight) {
var animationDuration = getRandomInt(1000, 3000) / difficulty;
enemy.animate({
x: getRandomInt(0, gameWidth - enemyWidth),
y: getRandomInt(0, gameHeight - enemyHeight)
}, animationDuration, "ease-in-out");
// use setTimout instead of onAnimation callback, since it gave "too much recursion" in Firefox 3.6
this.timeOut = setTimeout(function() {
animateEnemies(enemy , enemyWidth , enemyHeight);
}, animationDuration);
};
减少函数调用和缓存变量对旧版浏览器有很大帮助,除此之外,代码看起来非常整洁。
关于javascript - 优化SVG游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4060118/