為了即將要弄的iphone遊戲,實在是不得不要來理解一下html5…
雖然開頭總是一頭霧水,總之還是先把它一部分一部分的拆開來慢慢了解,為了遊戲的需求,canvas理所當然就是我的第一個目標囉~
canvas如他字面意思就是一張畫布,所以想要讓他變成像是flash一樣的動畫就得先為他加上時間軸,我是把它想像成小時候我們有時會畫在書角的小人一樣,當快速翻動時,人,就可以動起來了!
以下是實現時間軸的code:
function init(){
canvas = document.getElementById("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
canvas.addEventListener("click",ctxOnClick,false);
ctx = canvas.getContext('2d');
//時間軸
setInterval(drawCanvas, 1000/FPS);
}
function drawCanvas(){
//sceneTime --;
// console.log(sceneTime);
for(i=0;i
也就是說,每執行一次drawCanvas,就要把canvas清空一次,然後再從「更新過」的objarr陣列中,一一把東西再畫出來。
問題來了,objarr陣列裡面是麼東西?
html5本身(好像)並沒有元件的概念,只好用function代替object來達到用物件導向的目的。
var movClip = function(src,x,y,w,h,a){
this.init.apply(this, arguments);
this.animation_queue = [];
this.fillstyle = [];
}
movClip.prototype={
//「物件」初始化
init: function(src,x,y,a,w,h){
this.dx = x?x:0;
this.dy = y?y:0;
this.da = a?a:100;
this.da = a==0?0:this.da;
this.dw = w?w:null;
this.dh = h?h:null;
//j_fillrect-r-g-b-a
this.fillstyle = src.split("-");
this._img = src;
ctx.save();
this.fs = "rgba("+this.fillstyle[1]+", "+this.fillstyle[2]+", "+this.fillstyle[3]+", "+this.fillstyle[4]+")";
ctx.fillStyle = this.fs;
ctx.fillRect(this.dx,this.dy,this.dw,this.dh);
ctx.restore();
}
},
//在canvas中把「自己」畫出來
draw: function() {
ctx.save();
......
ctx.fillStyle = this.fs;
ctx.fillRect(this.mx,this.my,this.mw,this.mh);
ctx.restore();
},
//更新狀態
update:function(){
var animations_to_run_again = [];
for(animation in this.animation_queue){
var run_again = this.animation_queue[animation].call(this);
if(run_again){
animations_to_run_again.push(this.animation_queue[animation]);
}
}
this.animation_queue = animations_to_run_again;
}}
然後在html中實作物件:
$(document).ready(function() {
init();
r1 = new movClip("j_fillrect-0-0-0-0.65",0,0,100,240,90);
r2 = new movClip("j_fillrect-0-0-100-0.65",0,100,100,240,90);
r3 = new movClip("j_fillrect-0-100-0-0.65",0,200,100,240,90);
r4 = new movClip("j_fillrect-100-0-0-0.65",0,300,100,240,90);
objarr = [r1,r2,r3,r4];
});
這邊只是靜態的畫出四個正方形,物件的動態需要在另外用function來實現,但經過測試後,在pc跟iphone4s的表現都很不錯,iphone4差強人意,iphone3gs就已經慘不忍睹了.....。所以如果真要把html5當做flash來用,除了很多基本的改變位置,大小,透明都必須要在定義該物件的身上在寫入function之後,幫該function在update()加入監聽器來改變自己的屬性。其實真的是一件很花時間的工程阿.....