$30 off During Our Annual Pro Sale. View Details »

HTML5 canvas game

HTML5 canvas game

Write a game using canvas

Avatar for HakumaNatata

HakumaNatata

May 02, 2011
Tweet

More Decks by HakumaNatata

Other Decks in Programming

Transcript

  1. ¨  var canvas = document.getElementById("demo"); ¡  取得畫框 ¨  var ctx

    = canvas. getContext("2d"); ¡  放上白紙 ¡  Q: Is there a 3D canvas?
  2. ¨  畫線 ¨  ctx.beginPath(); //拿起一枝筆 ¨  ctx.moveTo(10,10); //放到紙上某一點 ¨  ctx.lineTo(50,50);

    //從目前位置畫到某一點 ¨  ctx.lineTo(10,50); ¨  ctx.closePath(); //將目前的點與原點連接起來 ¨  ctx.stroke(); //描外框 ¨  ctx.fillStyle = "rgb(R,G,B)"; //0~255 ¨  ctx.fill(); //填滿(自動執行 closePath())
  3. ¨  畫方形 ¨  ctx.fillStyle = "rgba(R,G,B,A)"; a = 0~1 ¨ 

    ctx.fillRect ( x1 , y1 , x2 , y2 ); ¨  ctx.clearRect ( x1 , y1 , x2 , y2 );
  4. ¨  畫圓 ¨  arc(x,y,r,startAngle,closeAngle,anticlockwise) ¨  弧度 弧度(逆時針) boolen ¨  ctx.beginPath();

    ¨  ctx.arc(275,300,100,Math.PI,Math.PI*3/2,true); ¨  ctx.lineTo(275,300); ¨  ctx.closePath(); ¨  ctx.stroke(); ¨  ctx.fill();
  5. ¨  Quick change alarge number of graphs. ¨  FPS (Frames

    Per Second) ¨  setInterval( action , time); // millisecond
  6. ¨  var player = { ¨  color: "#00A", ¨  x:

    220, ¨  y: 270, ¨  width: 32, ¨  height: 32, ¨  draw: function() ¨  { ¨  canvas.fillStyle = this.color; ¨  canvas.fillRect(this.x, this.y, this.width, this.height); ¨  } ¨  };
  7. ¨  function update() { if (keydown.space) { player.shoot(); } if

    (keydown.left) { player.x -= 5; } if (keydown.right) { player.x += 5; } player.x = Math.min(Math.max(player.x, 0), CANVAS_WIDTH - player.width); }
  8. ¨  player.shoot = function() { var bulletPosition = { x:

    this.x + this.width/2, y: this.y + this.height/2 }; playerBullets.push(Bullet({ speed: 5, x: bulletPosition.x, y: bulletPosition.y })); };
  9. ¨  //更新每個子彈狀態 ¨  playerBullets.forEach( function(bullet) {bullet.update(); } ); ¨  //過濾已經不行的子彈

    filter會回傳改過的陣列 而不會更動原本的陣列 ¨  playerBullets = playerBullets.filter( function(bullet) {return bullet.active; } );
  10. ¨  enemies.forEach(function(enemy) { enemy.update(); }); ¨  enemies = enemies.filter(function(enemy) {

    return enemy.active; }); ¨  if(Math.random() < 0.05) { enemies.push(Enemy()); }
  11. ¨  function collides(a, b) { return a.x < b.x +

    b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; }
  12. ¨  function handleCollisions() { playerBullets.forEach(function(bullet) { enemies.forEach(function(enemy) { if (collides(bullet,

    enemy)) { enemy.explode(); bullet.active = false; } }); }); enemies.forEach(function(enemy) { if (collides(enemy, player)) { enemy.explode(); } }); }