最近想寫一個簡單的手機RPG遊戲,現在的RPG製作工具多爲PC版,但Web版RPG製作太少了。網上的Scratch製作雖然簡單好用,但卻用的是flash,對手機來說是很不良好的。
打算寫一個Canvas的RPG遊戲,HTML5遊戲對手機遊戲製作好處不多說。
首先,創建一個Canvas。
標籤meta,這個對手機開發來說是需要的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta charset="utf-8">
<title>YHH Game</title>
<style>
body{
overflow:hidden
}
#gameCanvas{
display:block;
//border: 8px solid #123;
}
</style>
</head>
<body>
<canvas id="gameCanvas" ></canvas>
<script type="text/javascript" src="js/game.js" ></script>
</body>
</html>
然後,設置這個canvas
var main_canvas = document.getElementById("gameCanvas");
var main_context = main_canvas.getContext("2d");
var width = screen.width*0.92; //最大屏寬度
var height = screen.height*0.8; //最大屏高度
main_canvas.width = width;
main_canvas.height = height;
使用RequestAnimationFrame,這個是重點,按當前顯示屏刷新次數運到,一般的電腦屏是60Hz,就是每秒刷新60次,大概16.6m運行一次。
比起setTimeout和setInterval,RequestAnimationFrame不需要設置時間間隔,與顯示器刷新相同,運行更加流暢。
//main
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
var now = Date.now();
var then = Date.now();
var main = function () {
now = Date.now();
var delta = now - then; //時間間隔
then = now;
//寫運行內容
requestAnimationFrame(main);
};
main();