码迷,mamicode.com
首页 > Web开发 > 详细

第七讲:HTML5中的canvas两个小球全然弹性碰撞

时间:2014-07-22 22:34:35      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   os   width   

<html>
	<head>
		<title>小球之间的碰撞(全然弹性碰撞)</title>
		<script src="../js/jscex.jscexRequire.min.js" type="text/javascript"></script>
	</head>
	
	<body>
		<canvas id="mc" width="1200px" height="600px">
		</canvas>
		<script type="text/javascript">
			var canvas = document.getElementById('mc');
			var cxt = canvas.getContext('2d');
			//设置画布背景颜色
			cxt.fillStyle = "#030303";
   	 	cxt.fillRect(0, 0, canvas.width, canvas.height);
			var cyc = 20;
			var balls = [];
			//定义一个向x轴正前方运动
			var ball_1 = {
				x:100,
				y:550,
				r:50,
				vx:500,
				vy:0
			};
			//定义一个向x轴反方向运动
			var ball_2 = {
				x:1000,
				y:550,
				r:50,
				vx:-400,
				vy:0
			};
			balls.push(ball_1);
			balls.push(ball_2);
			cxt.fillStyle = "#030303";
			cxt.fillRect(0,0,canvas.width,canvas.height);
			//画出两个小球
			function init () {
				cxt.fillStyle = "#fff";
				for(var i in balls){
					cxt.beginPath();
					cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2,true);
					cxt.closePath();
					cxt.fill();
				}	
			}
			init();
			var ct 
			//动态绘出小球相碰撞的情形
			var somethingAsync = eval(Jscex.compile("async", function (ct) {
				while (true) {
					cxt.fillStyle = "rgba(0,0,0,1)";
					cxt.fillRect(0,0,canvas.width,canvas.height);
					cxt.fillStyle = "#fff";
					//小球运动
					for(var i in balls){
						balls[i].x += balls[i].vx *cyc /1000;
						cxt.beginPath();
						cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2,true);
						cxt.closePath();
						cxt.fill();
						//小球触碰左右两个墙壁
						if(balls[i].x + balls[i].r >= canvas.width || balls[i].x <= balls[i].r){
							balls[i].vx *= -1;
						}
					}
					//推断两个小球是否相互碰撞
					if(Math.abs(ball_1.x - ball_2.x) <= 2*50){
						var temp = ball_1.vx;
								ball_1.vx = ball_2.vx;
								ball_2.vx = temp;
					}
					$await(Jscex.Async.sleep(cyc,ct));	
				}		
			}));
			//手动控制小球的运动
			function Button1_onclick() {
        ct.cancel();
      }
      function Button2_onclick() {
        ct = new Jscex.Async.CancellationToken();
        somethingAsync(ct).start();
      }
      
		</script>
		<br>
		<br />
     <br />
     <input id="Button2" class="css3btn" type="button" value="run" onclick="return Button2_onclick()" />
     <input id="Button1" class="css3btn" type="button" value="stop" onclick="return Button1_onclick()" />

	</body>
</html>

bubuko.com,布布扣

第七讲:HTML5中的canvas两个小球全然弹性碰撞,布布扣,bubuko.com

第七讲:HTML5中的canvas两个小球全然弹性碰撞

标签:style   blog   http   java   os   width   

原文地址:http://www.cnblogs.com/yxwkf/p/3860965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!