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


    <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>

  • 相关阅读:
    GET 请求和 POST 请求
    爬虫
    模板继承
    静态文件配置
    终端cmd创建django
    商城商品分类导航效果
    css样式
    视图部分
    django初识和路由
    【源码分析】cocos2dx的Action
  • 原文地址:https://www.cnblogs.com/yxwkf/p/3860965.html
Copyright © 2020-2023  润新知