怎样用html5 canvas游戏源码制作一个简单的游戏

最近在学习HTML5,做了一个打砖块游戏。。。。
&!DOCUTYPE HTML&
打砖块. by 一只柯楠
&style type="text/css"&
border: 10
&h1&打砖块&/h1&
空格键:暂停;&br /&
方向左右键:控制接球板;&br /&
&canvas id="zn" width="480" height="760"&&/canvas&
&script type="text/javascript"&
var Brick= function () {
var requestAnim= window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { return setTimeout(callback, 100/6); },
cancelAnim= window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(timeid) { return clearTimeout(timeid); },
col= 8, row= 8, BW, BH= 30, BS= 1, r= 18, random= function (n1, n2) { return Math.round(Math.random()*(n2- n1))+n1},
elWidth, elHeight, cycle= 200, N= 0, score= 0,
randColor= function(c1, c2){ return 'rgb('+ random(c1 || 0, c2 || 255)+ ','+ random(c1 || 0, c2 || 255)+ ','+ random(c1 || 0, c2 || 255)+ ')'} ,
init = function (id) {
var el= this.el= document.querySelector(id);
elWidth= el.width, elHeight= el.
this.c= el.getContext('2d');
BW= +(elWidth/col-BS).toFixed(2);
this.RL= (elWidth- BW)/2;
this.RT= elHeight- BH- BS;
this.x= this.RL+ (BW/2);
this.y= elHeight-r- BH- BS;
this.xv= random(46, 90)* (Math.random()& .5 ? 2 : -2);
this.yv= -4* 126;
this.initBricks();
this.suspend=
this.listenerEvent();
init.prototype= {
start: function (timestamp) {
var self= this, newTime= Date.now(), diffX, diffY, diffTime= newTime- (timestamp || newTime) , x,
if(++N=== cycle){
var ary= [];
this.tables.unshift(ary);
for(var i =0 ; i& i++){
ary.push(1);
diffX= this.xv* diffTime/1000;
diffY= this.yv* diffTime/1000;
this.clearView();
//绘制砖块
this.drawBricks();
//绘制小球
this.drawBall(0, 0);
//绘制接球板
this.drawRacket();
//绘制得分
this.showText(score);
if(this.downKeyLeft)
this.RL= Math.max(this.RL- BW/5, 0);
else if(this.downKeyRight)
this.RL= Math.min(this.RL+ BW/5, elWidth- 2*BW);
x= this.x+ diffX;
y= this.y+ diffY;
if(x- r &0 || x+ r & elWidth)
this.xv *= -1;
if(y- r& 0)
this.yv *= -1;
else if(y+ r& this.RT){
if(x+ r& this.RL && x-r& this.RL+ 2*BW)
this.yv *= -1;
this.suspend=
this.clearView();
this.showText('GAME OVER');
var i= Math.floor(x/(BW +BS)), j= Math.floor(y/(BH +BS));
if(this.tables[j] && this.tables[j][i]===1){
this.tables[j][i]= 0;
score+= 100;
this.yv*=-1;
if(!this.suspend){
this.animID= requestAnim(function () {
self.start(newTime);
clearView: function () {
var c= this.c;
c.clearRect(0, 0, elWidth, elHeight);
initBricks: function(){
this.tables= [];
for(var i=0; i& i++){
this.tables.push([]);
for(var j=0; j& j++){
this.tables[i][j]= 1;
drawRacket: function () {
this.drawRect(this.RL, this.RT, 2*BW, BH, 1, 1);
drawBall: function(c1, c2){
var c= this.c;
c.beginPath();
c.arc(this.x, this.y, r, 0, 2*Math.PI);
c.fillStyle= '#000'//randColor(c1 || 150, c2 || 255);
c.closePath();
drawRect: function(x, y, w, h, c1, c2){
var c= this.c;
c.beginPath();
c.fillStyle= randColor(c1 || 0, c2 || 255);
c.closePath();
c.fillRect(x, y, w, h);
drawBricks: function(){
var i= 0,len= this.tables.length, cur, tables= this.
for(; i& i++){
cur= tables[i];
for(var j= 0; j& cur. j++){
cur[j]===1 && this.drawRect(j*(BW+ BS), i*(BH+ BS), BW, BH);
listenerEvent: function(e){
document.addEventListener('keydown', this, false);
document.addEventListener('keyup', this, false);
handleEvent: function(e){
var type= e.type, keycode= e.keyC
if(keycode===37 || keycode=== 39 || keycode=== 32){
switch(type){
case 'keydown':
if(keycode === 37) this.downKeyLeft=
else if(keycode===39)
this.downKeyRight =
case 'keyup':
if(keycode === 37)
this.downKeyLeft=
else if (keycode===39)
this.downKeyRight = false
this.suspend= !this.
!this.suspend && this.start();
showText: function(txt, left, top, size){
var c= this.c,
size = size || 60;
c.beginPath();
c.font= size+ 'pt Calibri';
tw= c.measureText(txt).
left= left=== undefined ? (elWidth- tw)/2 :
top= top=== undefined ? (elHeight- size)/2 :
c.fillText(txt, left, top);
c.closePath();
b= new Brick('#zn');
b.start();
阅读(...) 评论()用HTML5制作一个简单的桌球游戏的教程
作者:佚名
字体:[ ] 来源:互联网 时间:05-12 16:56:04
这篇文章主要介绍了用HTML5制作一个简单的桌球游戏的教程,主要利用到了HTML5的Canvas API,需要的朋友可以参考下
话说这只是一个简单的DEMO。游戏性,游戏规则什么的我都没怎么考虑,如果有兴趣细化的朋友可以细化一下,比如细化一下规则,游戏开关,加个声音,细化一下进球检测,更严谨甚至可以去查下击球力度、桌面真实摩擦力等来把游戏弄的更像游戏。我只是给个编程思路哈,随便坐个DEMO而已,玩起来估计还是不会很爽快的~~
 整个桌球游戏就两个类,一个是球,一个是辅助瞄准线。如果想把改游戏弄的更复杂,还可以再抽象一个形状类,用于检测球与边角的碰撞以及进球。我做的这个游戏采取了最简单的墙壁碰撞检测,所以没有进行球与不规则形状的碰撞检测,如果想玩更复杂的碰撞,可以戳
岑安大大讲的还是很好的。好,接下来就一步一步来:
  【球】
  先贴代码:[/code]var Ball = function(x , y , ismine){&&&&&&&&&&& this.x =&&&&&&&&&&& this.y =&&&&&&&&&&& this.ismine =&&&&&&&&&&& this.oldx =&&&&&&&&&&& this.oldy =&&&&&&&&&&& this.vx = 0;&&&&&&&&&&& this.vy = 0;&&&&&&&&&&& this.radius = ballR&&&&&&&&&&& this.inhole =this.moving =&&&&&&& }&&&&&&& Ball.prototype = {&&&&&&&&&&& constructor:Ball,&&&&&&&&&&& _paint:function(){&&&&&&&&&&&&&&& var b = this.ismine?document.getElementById(&wb&) : document.getElementById(&yb&)&&&&&&&&&&&&&&& plete) {&&&&&&&&&&&&&&&&&&& ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&& else {&&&&&&&&&&&&&&&&&&& b.onload = function(){&&&&&&&&&&&&&&&&&&&&&&& ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&& }&&&&&&&&&&& },&&&&&&&&&&& _run:function(t){&&&&&&&&&&&&&&& this.oldx = this.x;&&&&&&&&&&&&&&& this.oldy = this.y;
&&&&&&&&&&&&&&& this.vx = Math.abs(this.vx)&0.1? 0 : (this.vx&0? this.vx-mcl*t : this.vx+mcl*t);&&&&&&&&&&&&&&&& this.vy = Math.abs(this.vy)&0.1? 0 : (this.vy&0? this.vy-mcl*t : this.vy+mcl*t);&&&&&&&&&&&&&&& // this.vx += this.vx&0? -mcl*t : mcl*t;&&&&&&&&&&&&&&& // this.vy += this.vy&0? -mcl*t : mcl*t;
&&&&&&&&&&&&&&&& this.x += t * this.vx *&&&&&&&&&&&&&&&& this.y += t * this.vy *
&&&&&&&&&&&&&&&& if((this.x&50 && this.y&50) || (this.x&370 && this.x&430 && this.y&50) || (this.x & 758 && this.y&50) || (this.x&46 && this.y&490) || (this.x&377 && this.x&420 && this.y&490) || (this.x & 758 && this.y&490)){&&&&&&&&&&&&&&&&&&&& this.inhole =&&&&&&&&&&&&&&&&&&&& if(this.ismine){&&&&&&&&&&&&&&&&&&&&&&&& var that =&&&&&&&&&&&&&&&&&&&&&&&& setTimeout(function(){&&&&&&&&&&&&&&&&&&&&&&&&&&&& that.x = 202;&&&&&&&&&&&&&&&&&&&&&&&&&&&& that.y = canvas.height/2;&&&&&&&&&&&&&&&&&&&&&&&&&&&& that.vx = 0;&&&&&&&&&&&&&&&&&&&&&&&&&&&& that.vy = 0;&&&&&&&&&&&&&&&&&&&&&&&&&&&& that.inhole =&&&&&&&&&&&&&&&&&&&&&&&& } , 500)&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&&& else {&&&&&&&&&&&&&&&&&&&&&&&& document.getElementById(&shotNum&).innerHTML = parseInt(document.getElementById(&shotNum&).innerHTML)+1&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&& else {&&&&&&&&&&&&&&&&&&&& if(this.y & canvas.height - (ballRadius+tbw) || this.y & (ballRadius+tbw)){&&&&&&&&&&&&&&&&&&&&&&&& this.y = this.y & (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.height - (ballRadius+tbw));&&&&&&&&&&&&&&&&&&&&&&&& this.derectionY = !this.derectionY;&&&&&&&&&&&&&&&&&&&&&&&& this.vy = -this.vy*0.6;&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&&&&&& if(this.x & canvas.width - (ballRadius+tbw) || this.x & (ballRadius+tbw)){&&&&&&&&&&&&&&&&&&&&&&&& this.x = this.x & (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.width - (ballRadius+tbw));&&&&&&&&&&&&&&&&&&&&&&&& this.derectionX = !this.derectionX;&&&&&&&&&&&&&&&&&&&&&&&& this.vx = -this.vx*0.6;&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&& this._paint();
&&&&&&&&&&&&&&&& if(Math.abs(this.vx)&0.1 && Math.abs(this.vy)&0.1){&&&&&&&&&&&&&&&&&&&& this.moving =&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&& else {&&&&&&&&&&&&&&&&&&&& this.moving =&&&&&&&&&&&&&&&& }&&&&&&&&&&& }&&&&&&& }[/code]&球类的属性:x,y球的位置,vx,vy球的水平速度以及求得垂直速度,ismine代表是白球还是其他球(不同球在_paint方法中绘制的图片不一样),oldx,oldy用于保存球的上一帧位置,不过暂时还没用上,应该有用吧。_paint方法没什么好说的,_run方法就是跟踪小球位置,根据小球每一帧的时间来算出小球的位移增量以及速度增量,mcl和pxpm都是常量,mcl是摩擦力,pxpm是大概算个像素和现实转换比例。。。。然后就是碰撞检测,这个很容易理解了,就计算小球的位置有没有超过边界,超过了就反弹。不过这种碰撞检测很不严谨,如果真要做游戏建议用更复杂一些的。还有就是根据小球的速度来让小球静止。&代码如下:var dotLine = function(x0,y0,x1,y1){
this.x0 = this.x0;
this.y0 = this.y0;
this.x1 = this.x1;
this.y1 = this.y1;
this.dotlength = 3;
this.display =
dotLine.prototype = {
constructor:dotLine,
_ready:function(){
this.length = Math.sqrt(Math.pow(this.y1 - this.y0 , 2)+Math.pow(this.x1 - this.x0 , 2));
this.dotNum = Math.ceil(this.length/this.dotlength);
_paint:function(){
this._ready();
xadd = this.dotlength*(this.x1 - this.x0)/this.
yadd = this.dotlength*(this.y1 - this.y0)/this.
ctx.save();
ctx.beginPath();
for(var i=1;i&=this.dotNi++){
if(i%2!==0){
ctx.moveTo(this.x0+(i-1)*xadd , this.y0+(i-1)*yadd);
ctx.lineTo(this.x0+i*xadd , this.y0+i*yadd);
ctx.strokeStyle = "#FFF";
ctx.stroke();
ctx.beginPath();
ctx.arc(this.x1 , this.y1 , ballRadius-2 , 0 , 2*Math.PI);
ctx.stroke();
ctx.restore();
}&就是画虚线,这个比较简单了,获取鼠标的位置和白球位置,然后在两者之间隔一段距离画条线,然后就成虚线了。
  【多球碰撞检测】代码如下:function collision(){
for(var i=0;i&balls.i++){
for(var j=0;j&balls.j++){
var b1 = balls[i],b2 = balls[j];
if(b1 !== b2 && !b1.inhole && !b2.inhole){
var rc = Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2));
if(Math.ceil(rc) & (b1.radius + b2.radius)){
if(!b1.moving && !b2.moving)
//获取碰撞后的速度增量
var ax = ((b1.vx - b2.vx)*Math.pow((b1.x - b2.x) , 2) + (b1.vy - b2.vy)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
var ay = ((b1.vy - b2.vy)*Math.pow((b1.y - b2.y) , 2) + (b1.vx - b2.vx)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)                //将速度增量赋给碰撞小球
b1.vx = b1.vx-
b1.vy = b1.vy-
b2.vx = b2.vx+
b2.vy = b2.vy+                //修正小球碰撞距离
var clength = ((b1.radius+b2.radius)-rc)/2;
var cx = clength * (b1.x-b2.x)/
var cy = clength * (b1.y-b2.y)/
b1.x = b1.x+
b1.y = b1.y+
b2.x = b2.x-
b2.y = b2.y-
}&对所有小球进行遍历,计算两个小球的球心距离,如果小于两小球的半径和,则说明发生了碰撞。如果两个小球都是静止的,就不进行碰撞检测,否则进行计算碰撞后的速度增量,碰撞速度增量的求法可以直接看
,里面讲的挺详细的,综合起来就得出了上面那一串式子了。
  将速度增量赋给碰撞小球。因为两个球碰撞那一帧,两个球是有部分重叠的,所以得进行位置修正,不然小球会一直处于碰撞然后就黏在一起了,位置修正的原理也简单,算出两球的球心距离,通过勾股定理计算出两球的重叠区域的宽度,然后把宽度除于2后赋给小球新的位置,新的位置就是两个球的半径刚好等于球心距。
  【鼠标动作】代码如下:canvas.addEventListener("mousedown" , function(){
if(balls[0].moving)&/p&
document.querySelector(".shotPower").style.display = "block";
document.querySelector(".shotPower").style.top = balls[0].y-60 + "px";
document.querySelector(".shotPower").style.left = balls[0].x-40 +"px";
document.getElementById("pow").className = "animate";
var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetL
var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetT
dotline.display =
dotline.x0 = balls[0].x;
dotline.y0 = balls[0].y;
dotline.x1 =
dotline.y1 =&/p&
window.addEventListener("mouseup" , muHandle , false);
window.addEventListener("mousemove" , mmHandle , false);&/p&
function mmHandle(){
var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetL
var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetT
dotline.x1 =
dotline.y1 =
function muHandle(){
var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetL
var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetT&/p&
var angle = Math.atan((y - balls[0].y)/(x - balls[0].x));
var h = document.getElementById("pow").offsetHeight/document.getElementById("powbar").offsetH
var v = 60*h;
document.getElementById("pow").style.height = h*100+"%"&/p&
balls[0].vx = x - balls[0].x&0 ? v*Math.abs(Math.cos(angle)) : -v*Math.abs(Math.cos(angle));
balls[0].vy = y - balls[0].y&0 ? v*Math.abs(Math.sin(angle)) : -v*Math.abs(Math.sin(angle));&/p&
document.getElementById("pow").className = "";&/p&
window.removeEventListener("mouseup" , muHandle , false);
window.removeEventListener("mousemove" , muHandle , false);
dotline.display =
document.querySelector(".shotPower").style.display = "none";
},false);&鼠标动作也比较简单,有js基础的基本上都没问题,就是鼠标按下后计算鼠标位置,然后产生辅助虚线,鼠标移动后修改辅助虚线的终点位置。鼠标按下的时候旁边产生一个力量计,我就只用用animation做动画了,然后鼠标按键抬起时通过计算力量计的大小来确定白球的速度,然后再分解成水平速度以及垂直速度赋给白球。同时取消鼠标移动以及鼠标抬起的事件绑定,把辅助虚线以及力量计隐藏。
  【动画舞台】
&&&&&代码如下:
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height)
var t1 = new Date();
var t = (t1 - t0)/1000;&/p&
collision();
balls.foreach(function(){
if(!this.inhole) this._run(t);
if(dotline.display){
dotline.x0 = balls[0].x;
dotline.y0 = balls[0].y;
dotline._paint();
if(!animateStop){
if("requestAnimationFrame" in window){
requestAnimationFrame(animate);
else if("webkitRequestAnimationFrame" in window){
webkitRequestAnimationFrame(animate);
else if("msRequestAnimationFrame" in window){
msRequestAnimationFrame(animate);
else if("mozRequestAnimationFrame" in window){
mozRequestAnimationFrame(animate);
setTimeout(animate , 16);
}&这个就是游戏每一帧的逻辑处理现场,如果小球进洞了,就不再进行绘制,如果辅助虚线的display属性设成false,就不进行辅助虚线的绘制,还有就是计算每一帧的时间。 【常量与初始化】&代码如下: var canvas = document.getElementById("cas");
var ctx = canvas.getContext('2d');
var mcl = 1 , collarg = 0.8 , ballRadius = 15 , t0 = 0 , balls=[] , tbw = 32 , animateStop = true , powAnimation =
pxpm = canvas.width/20;&/p&
window.onload = function(){
var myball = new Ball(202 , canvas.height/2 , true);
balls.push(myball);
for(var i=0;i&6;i++){
for(var j=0;j&i;j++){
var other = new Ball(520+i*(ballRadius-2)*2 , (canvas.height-i*2*ballRadius)/2+ballRadius+2*ballRadius*j , false);
balls.push(other);
t0 = new Date();
dotline = new dotLine(0,0,0,0);&/p&
animateStop =
animate();
}&实例化所有小球,把小球全部按照规律摆好,然后获取当前时间,实例化辅助虚线,动画开始。
源码地址:
大家感兴趣的内容
12345678910
最近更新的内容

我要回帖

更多关于 html5 canvas游戏开发 的文章

 

随机推荐