<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" οnclick="return Button2_onclick()" /><input id="Button1" class="css3btn" type="button" value="stop" οnclick="return Button1_onclick()" /></body>
</html>
本文主要是介绍第七讲:HTML5中的canvas两个小球全然弹性碰撞,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这篇关于第七讲:HTML5中的canvas两个小球全然弹性碰撞的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!