第七讲: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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。