实现小球弹性碰撞

<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <title>Document</title>

  <style type="text/css">

  canvas{

    border: 2px solid red;

  }

  </style>

  <script type="text/javascript">

   window.οnlοad=function(){

    var hspeed1=6;

    var vspeed1=6;

    var hspeed2=6;

    var vspeed2=6;

    var x1=200;

    var y1=0;

     var x2=0;

    var y2=100;

    var rad=20;

    var timer1=null;

    var timer2=null;

    var txt=document.getElementById("canvas").getContext("2d");

    document.getElementById("btn").οnclick=function(){

      clearInterval(timer1);

      clearInterval(timer2);

       timer1=setInterval(function(){

        txt.clearRect(0,0,400,400)

       x1+=hspeed1;

       y1+=vspeed1;

       txt.beginPath()

       txt.fillStyle="rgb(21,122,222)";

       txt.arc(x1,y1,rad,0,2*Math.PI,true);

       txt.closePath();

       txt.fill();

       if(x1>=395){

        hspeed1=-hspeed1;

       }

       if(y1>=395){

        vspeed1=-vspeed1;

       }

       if(x1<=5){

         hspeed1=-vspeed1;

       }

       if(y1<=5){

        vspeed1=-vspeed1;

       } 

  },100);

       timer2=setInterval(function(){

       x2+=hspeed2;

       y2+=vspeed2;

       txt.beginPath();

       txt.fillStyle="rgb(22,22,123)";

       txt.arc(x2,y2,rad,0,2*Math.PI,true);

       txt.closePath();

       txt.fill();

      if(x2>=395){

        hspeed2=-hspeed2;

       }

       if(y2>=395){

        vspeed2=-vspeed2;

       }

       if(x2<=5){

         hspeed2=-hspeed2;

       }

       if(y2<=5){

        vspeed2=-vspeed2;

       }

       },100)  

    } 

  document.getElementById("stop").οnclick=function(){

    clearInterval(timer1);

     clearInterval(timer2);

  }

   }

  </script>

</head>

<body>

 <canvas width="400px" height="400" id="canvas"></canvas>

 <input type="button" id="btn" value="开始运动">

 <input type="button" id="stop" value="停止运动">

</body>

</html>


转载于:https://my.oschina.net/u/2604302/blog/597148

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值