今天花點時間研究昨日的切換場景,寫個簡易的場景管理器
簡易場景切換 Demo with ScenesManager
1.製作一個場景為四方形的物體場景
function drawRec(){
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
2.製作一個場景三角形的物體場景
function drawTri() {
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// Filled triangle
ctx.beginPath();
ctx.moveTo(25,25);
ctx.lineTo(105,25);
ctx.lineTo(25,105);
ctx.fill();
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke();
}
}
3.今日主角 ScenceManager
class ScenesManager {
constructor() {
this.scenes = {} // 紀錄 create 過的場景
this.currentScene = null // 當前場景
}
create = (width, height, scale=false) => {
var canvas = document.getElementById('canvas')
canvas.width = width
canvas.height = height
return this;
}
createScene(id, TScene) {
scenesManager.scenes[id] = TScene;
}
clearScene() {
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
goToScene(id) {
this.clearScene() // 清除上一個場景
if (scenesManager.scenes[id]) {
scenesManager.currentScene = scenesManager.scenes[id];
scenesManager.scenes[id]()
return true;
}
return false;
}
}
4.使用過程
const scenesManager = new ScenesManager()
scenesManager.create(150, 150, true)
var rec = scenesManager.createScene('rectangle', drawRec);
var tri = scenesManager.createScene('triangle', drawTri);
$('#goToRec').click(function () {
scenesManager.goToScene('rectangle');
});
$('#goToTri').click(function () {
scenesManager.goToScene('triangle');
});
scenesManager.goToScene('rectangle');
5.Demo 結果