`
128kj
  • 浏览: 583799 次
  • 来自: ...
社区版块
存档分类
最新评论

HTML5 Canvas学习笔记(7)俄罗斯方块游戏之一(色块)

阅读更多
在网上看到一个俄罗斯方块游戏:
http://www.108js.com/article/article11/b0044.html
感觉还不错,学习了它的源码,写点笔记。俗话说:熟读唐诗三百首,不会吟诗也会吟。我相信熟读源码三百个,不会编程也会编。

这个俄罗斯方块游戏的精华部分应该是三个类,先看这个第一个Block类:
(function(){
   // Single Tetris Block
  function Block(image){
    this.image =image;//图像
    this.size  =32;//每个色块的大小32*32
    this.total = 7;//有七种颜色的块
   }

   Block.prototype = {
     random: function(){//产生一个随机数1-7
       return Math.floor( Math.random() * this.total ) + 1;
     },
     draw: function(context, x, y, blockType){//绘制这个块,x与y是网格坐标
       var blockType = blockType || this.random();//块的类型
       var s = this.size;
       context.drawImage(this.image, (blockType-1)*s, 0, s, s, s*x, s*y, s, s);
     }
   }
  window.Block=Block;
})();

类中用到的图片:



下面是测试代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="gbk">

<title>俄罗斯方块:色块测试</title>
<style>
        canvas {
  display: block;
  position: absolute;
  background: rgba(20,20,20,0.8);
         border: 2px solid yellow;
         border-radius: 10px;
        }
      </style>


</head>
<body>
<div class="container">
<canvas id="board" width="416" height="640">Your browser doesn't support Canvas</canvas>

</div>
</body>
<script>
(function(){
   // Single Tetris Block
  function Block(image){
    this.image =image;//图像
    this.size  =32;//每个色块的大小32*32
    this.total = 7;//有七种颜色的块
   }

   Block.prototype = {
     random: function(){//产生一个随机数1-7
       return Math.floor( Math.random() * this.total ) + 1;
     },
     draw: function(context, x, y, blockType){//绘制这个块,x与y是网格坐标
       var blockType = blockType || this.random();//块的类型
       var s = this.size;
       context.drawImage(this.image, (blockType-1)*s, 0, s, s, s*x, s*y, s, s);
     }
   }
  window.Block=Block;
})();

   var el= document.getElementById("board");
   var ctx = el.getContext('2d');
  
 
  var image = new Image();
  image.src = "img/blocks.png";
  image.onload=init;//图像加载完毕后执行
  var block=null;
  function init(){
    block=new Block(image);
    //canvas的大小为宽13*32,高为20*32
    block.draw(ctx,3,3);
  }
</script>

效果图:


点击看效果:http://www.108js.com/article/canvas/7/1/e1.html

欢迎访问博主的网站:http://www.108js.com

下载本学习笔记的源码:
  • 大小: 5.7 KB
  • 大小: 9.3 KB
  • 1.zip (8.4 KB)
  • 下载次数: 7
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics