canvas教程

用Canvas写桌球游戏(4)

字号+ 作者:H5之家 来源:H5之家 2017-10-29 18:28 我要评论( )

昨天上班的时候闲着无事,就用Canvas写了个桌球游戏来玩玩。。。。所以就拿这游戏上来水一发 。或许对一些刚学canvas的人有帮助。 话说这只是一个简单的DEMO。

【常量与初始化】

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 = false; var dotline; pxpm = canvas.width/20; 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); animateStop = false; animate(); }

实例化所有小球,把小球全部按照规律摆好,然后获取当前时间,实例化辅助虚线,动画开始。

下面贴出全部代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF- 8"> <style> body{margin:0;padding:0;} .view{width: 800px;height: 544px;margin:20px auto;position: relative;} #cas{display: block;border:1px solid;background:url(image/table.jpg) no-repeat;} .shotPower{width: 30px;height: 80px;position: absolute;right: -80px;top: 150px;display: none} #powbar{width: 5px;height: 60px;margin:auto;background-color: #CCC;position: relative;} #pow{width: 100%;height:50%;position: absolute;bottom: 0px;} #maxPower{color: #FFF;text-align: center;width: 100%;padding-bottom:3px;font-size: 10px;} #powText{color: #FFF;text-align: center;width: 100%;padding-top: 3px;font-size: 8px;} .animate{-webkit-animation:add 2s infinite linear;} @-webkit-keyframes add{ 0%{height:0%;background-color:#ff0;} 50%{height:100%;background-color:#f00;} 100%{height:0%;background-color:#ff0;} } </style> <title>桌球游戏</title> </head> <body style="background-color: #000"> <div class="view"> <canvas id="cas" width="800" height="544">您的浏览器不支持canvas,请升级浏览器</canvas> <img src="image/white_ball.png" id="wb" alt="" style="display:none"/> <img src="image/yellow_ball.png" id="yb" alt="" style="display:none"/> <div class="shotPower"> <div id="maxPower">MAX</div> <div id="powbar"><div id="pow"></div></div> <div id="powText">power</div> </div> <div style="position:absolute;left:-100px;top:250px;color:#FFF">进球数:<span id="shotNum">0</span></div> </div> <script> 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 = false; var dotline; pxpm = canvas.width/20; 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); animateStop = false; animate(); } canvas.addEventListener("mousedown" , function(){ if(balls[0].moving) return; 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").offsetLeft; var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop; dotline.display = true; dotline.x0 = balls[0].x; dotline.y0 = balls[0].y; dotline.x1 = x; dotline.y1 = y; window.addEventListener("mouseup" , muHandle , false); window.addEventListener("mousemove" , mmHandle , false); function mmHandle(){ var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetLeft; var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop; dotline.x1 = x; dotline.y1 = y; } function muHandle(){ var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetLeft; var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop; var angle = Math.atan((y - balls[0].y)/(x - balls[0].x)); var h = document.getElementById("pow").offsetHeight/document.getElementById("powbar").offsetHeight; var v = 60*h; document.getElementById("pow").style.height = h*100+"% " 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)); document.getElementById("pow").className = ""; window.removeEventListener("mouseup" , muHandle , false); window.removeEventListener("mousemove" , muHandle , false); dotline.display = false; document.querySelector(".shotPower").style.display = "none"; } },false); function animate(){ ctx.clearRect(0,0,canvas.width,canvas.height) var t1 = new Date(); var t = (t1 - t0)/1000; 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(); } t0 = t1; 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); } else { setTimeout(animate , 16); } } } function collision(){ for(var i=0;i<balls.length;i++){ for(var j=0;j<balls.length;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) return; 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-ax; b1.vy = b1.vy-ay; b2.vx = b2.vx+ax; b2.vy = b2.vy+ay; var clength = ((b1.radius+b2.radius)-rc)/2; var cx = clength * (b1.x-b2.x)/rc; var cy = clength * (b1.y-b2.y)/rc; b1.x = b1.x+cx; b1.y = b1.y+cy; b2.x = b2.x-cx; b2.y = b2.y-cy; } } } } } 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 = false; } 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.length; yadd = this.dotlength*(this.y1 - this.y0)/this.length; ctx.save(); ctx.beginPath(); for(var i=1;i<=this.dotNum;i++){ 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(); } } var Ball = function(x , y , ismine){ this.x = x; this.y = y; this.ismine = ismine; this.oldx = x; this.oldy = y; this.vx = 0; this.vy = 0; this.radius = ballRadius; this.inhole = false; this.angle = 0; this.moving = true; } Ball.prototype = { constructor:Ball, _paint:function(){ var b = this.ismine?document.getElementById("wb") : document.getElementById("yb") if(b.complete) { 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 * pxpm; this.y += t * this.vy * pxpm; 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 = true; if(this.ismine){ var that = this; setTimeout(function(){ that.x = 202; that.y = canvas.height/2; that.vx = 0; that.vy = 0; that.inhole = false; } , 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.angle = Math.atan((this.x - this.oldx)/(this.y - this.oldy)) this._paint(); if(Math.abs(this.vx)<0.1 && Math.abs(this.vy)<0.1){ this.moving = false; } else { this.moving = true; } } } Array.prototype.foreach = function(callback){ for(var i=0;i<this.length;i++){ callback.apply(this[i] , [i]); } } var Line = function(x0,y0,x1,y1){ this.start = { x:x0, y:y0 } this.end = { x:x1, y:y1 } this.x = null; this.y = null; this.k = (y0 - y1)/(x0 - x1); this.b = y0 - this.k * x0; if(x0-x1===0){ this.x = x0; } if(y0-y1===0){ this.y = y0; } this.angle = Math.asin(this.k) this._draw = function(){ ctx.save(); ctx.beginPath(); ctx.moveTo(this.start.x , this.start.y); ctx.lineTo(this.end.x , this.end.y); ctx.stroke(); ctx.restore(); } } function getLineCols(line1 , line2){ if(line1.k - line2.k === 0){ return false; } var x , y; x = (line2.b - line1.b)/(line1.k - line2.k); y = line1.k * x + line1.b; if(line1.x!==null){ x = line1.x; y = line2.k * x + line2.b; } else if(line2.x !== null){ x = line2.x; y = line1.k * x + line1.b; } if(line1.y!==null){ y = line1.y; x = (y-line2.b)/line2.k } else if(line2.y !== null){ y = line2.y; x = (y-line1.b)/line1.k } if(((x>=line1.start.x && x<=line1.end.x)||(x>=line1.end.x && x<=line1.start.x))&&((y>=line1.start.y && y<=line1.end.y)||(y>=line1.end.y && y<=line1.start.y))){ if(((x>=line2.start.x && x<=line2.end.x)||(x>=line2.end.x && x<=line2.start.x))&&((y>=line2.start.y && y<=line2.end.y)||(y>=line2.end.y && y<=line2.start.y))){ return {x:x , y:y} } } return false; } </script> </body> </html>

底部的那两个方法是写两条线相交的判定和交点的获取,想用来写严谨一些的碰撞检测。

查看本栏目更多精彩内容:

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 微信小程序Canvas增强组件 相关介绍、文档、教程

    微信小程序Canvas增强组件 相关介绍、文档、教程

    2017-10-30 09:35

  • Canvas教程(16)

    Canvas教程(16)

    2017-10-29 15:00

  • Android Canvas编程:对rotate()和translate()两个方法的研究

    Android Canvas编程:对rotate()和translate()两个方法的研究

    2017-10-29 11:40

  • 天天学名言:Life is a great big canvas, and you should throw

    天天学名言:Life is a great big canvas, and you should throw

    2017-10-28 16:00

网友点评