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

本文通过分析一个在线俄罗斯方块游戏的源代码,详细介绍了游戏中关键的Block类,包括随机生成色块的方法及如何在画布上绘制这些色块。此外,还提供了完整的测试代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这个俄罗斯方块游戏的精华部分应该是三个类,先看这个第一个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;
})();

类中用到的图片:
[img]http://dl2.iteye.com/upload/attachment/0098/7563/2c1e6259-bb96-3733-baf5-c008af9aa788.png[/img]


下面是测试代码:
<!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.οnlοad=init;//图像加载完毕后执行
var block=null;
function init(){
block=new Block(image);
//canvas的大小为宽13*32,高为20*32
block.draw(ctx,3,3);
}
</script>

效果图:
[img]http://dl2.iteye.com/upload/attachment/0098/7569/d355a6a2-d72d-3ac2-8c29-083ab80b1210.gif[/img]

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

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

下载本学习笔记的源码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值