canvas动画,并可以用上下左右箭头控制方向,空格键是停止,代码如下

点击(此处)折叠或打开

  1. <!DOCTYPE html >
  2. <html>
  3.  <head>
  4.     <title>cars</title>
  5.     <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
  6.  </head>
  7.  <body>
  8.  <canvas id ="canvas" width="200" height="200"></canvas>
  9.  </body>
  10.  <script>
  11.  var canvas = document.getElementById("canvas");
  12.  var ctx = canvas.getContext("2d");
  13.  var width = canvas.width;
  14.  var height = canvas.height;
  15.  var circle = function(x,y,radius,fillCircle){
  16.     ctx.beginPath();
  17.     ctx.arc(x,y,radius,0,Math.PI*2,false);
  18.     if(fillCircle){
  19.      ctx.fill();
  20.     }else{
  21.      ctx.stroke();
  22.     }
  23.  }
  24.  //the ball constructor
  25.  var Ball = function(){
  26.     this.x = width/2;
  27.     this.y = height/2;
  28.     this.xSpeed = 5;
  29.     this.ySpeed = 0;
  30.  }
  31.  //update the ball's position based on its speed
  32.  Ball.prototype.move = function(){
  33.     this.x += this.xSpeed;
  34.     this.y += this.ySpeed;
  35. if(this.x
  36.     this.x = width;
  37.  }else if(this.x>width){
  38.     this.x =0;
  39.  }else if(this.y
  40.     this.y = height;
  41.  }else if(this.y >height){
  42.    this.y =0;
  43.  }
  44.  }
  45.  //draw the ball at its current position
  46.  Ball.prototype.draw = function(){
  47.    circle(this.x,this.y,10,true);
  48.  }
  49.  //set the ball's direction based on a string
  50.  Ball.prototype.setDirection = function(direction){
  51.     if(direction === "up"){
  52.      this.xSpeed = 0;
  53.      this.ySpeed = -5;
  54.     }else if(direction === "down"){
  55.      this.xSpeed = 0;
  56.      this.ySpeed = 5;
  57.     }else if(direction === "left"){
  58.      this.xSpeed = -5;
  59.      this.ySpeed = 0;
  60.     }else if(direction === "right"){
  61.      this.xSpeed = 5;
  62.      this.ySpeed = 0;
  63.     }else if(direction === "stop"){
  64.      this.xSpeed = 0;
  65.      this.ySpeed = 0;
  66.     }
  67.  }
  68.  //create the ball object
  69.  var ball = new Ball();
  70.  //an object to convert keycodes into action names
  71.  var keyActions = {
  72.     32:"stop",
  73.     37:"left",
  74.     38:"up",
  75.     39:"right",
  76.     40:"down"
  77.  };
  78.  //the keydown handler that will be called for every keypress
  79.  $("body").keydown(function(event){
  80.     var direction = keyActions[event.keyCode];
  81.     ball.setDirection(direction);
  82.  });
  83.  //the animation function,called every 30ms
  84.  setInterval(function(){
  85.    ctx.clearRect(0,0,width,height);
  86.    ball.draw();
  87.    ball.move();
  88.    ctx.strokeRect(0,0,width,height);
  89.  },30);
  90.  </script>
  91.  </html>

09-29 02:46