canvas制作运动的小球

<!DOCTYPE html>
<head>
<title>canvas</title>
<style>
.canvas{
   border: 1px solid #000;
}
</style>
</head>
<body>
<canvas class="canvas" id="canvas" width="400px" height="400px"></canvas>
<script>
window.onload=function(){
   var can=document.getElementById("canvas");
   var cxt=can.getContext("2d");
   var ball={
      x:100,
      y:100,
      vx:4,
      vy:2,
      radius:20,
      color:"blue",
      draw:function(){
        cxt.beginPath();
        cxt.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
        cxt.closePath();
        cxt.fillStyle=this.color;
        cxt.fill();
      }
   };   
   var draw=function(){
       cxt.clearRect(0,0,canvas.width,canvas.height);
       ball.draw();
       ball.x+=ball.vx;
       ball.y+=ball.vy;
       if(ball.vy+ball.y>canvas.height-15 || ball.vy+ball.y<15){
           ball.vy=-ball.vy;
       }
       if(ball.vx+ball.x>canvas.width-15 || ball.vx+ball.x<15){
           ball.vx=-ball.vx;
       }
       window.requestAnimationFrame(draw);
       //window.setTimeout(function(){
       //      draw();
       //},100);
   };
   
   draw();
   
};
</script>
</body>
</html>
View Code

原文地址:https://www.cnblogs.com/aliwa/p/6360223.html