代码改变世界

速度向量之单轴速度

2011-12-10 13:11  LoujaDy  阅读(313)  评论(0编辑  收藏  举报

源码

//获取到舞台
var canvas=document.getElementById("stage");
//舞台2d绘图接口
var context=canvas.getContext("2d");
//获取中心点置
var centerX=canvas.width/2;
var centerY=canvas.height/2;
//在舞台上画一条马路
context.lineWidth = 2;
context.strokeStyle = "#ff0000";
context.beginPath();
context.moveTo(0,centerY+2);
context.lineTo(centerX*2,centerY+2);
                 context.stroke();
                 context.closePath();
                 /**
                  * 向量对象
                  
*/
                 var Vector2d=function(x,y)
                 {
this.x=x;
this.y=y;
                 } 
                 /**
                  * 球对象
                  
*/
                 var Ball=function(x,y,radius,color)
                 {
//球的中心点位置
this.x=x;
this.y=y;
//球的半径
this.radius=radius;
//球的颜色
this.color=color;
//球的边框颜色
context.strokeStyle = color;
//球体颜色
context.fillStyle=color; 
/**
      * 绘制球
      
*/ 
this.draw=function()
{
context.beginPath(); 
                         context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); 
                         context.fill(); 
                         context.stroke();
                         context.closePath();
}
                 } 
                 //球的半径 
                 var rd=20;
                 //创建一个球对象,让球在马路的最左边
                 var ball=new Ball(rd+1,centerY-rd-1,rd,"#ccc"); 
                 //显示球
                 ball.draw(); 
var ballVector=null;
                 /**
                  * 开始按钮事件
                  
*/
                 function Run()
                 { 
                      //球运行的速度
                       ballVector=new Vector2d(2,0); 
                                     } 

 //动画
                     var drawAsync = eval(Jscex.compile("async", function () {
                                 while(true)
                                 {
                if(ballVector!=null)
{
//清空马路上方的区域
      context.clearRect(0,0, centerX*2, centerY);
      //球向右边行始
                                      ball.x+=ballVector.x;
                                      if(ball.x-rd>=centerX*2)
                                      {
ball.x=rd+1;
                                      }
                                      ball.draw();
}
                                      $await(Jscex.Async.sleep(1000/60));
                                  } 
                     }));
                     drawAsync().start();

 作者:Louja

出处:http://loujady.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此声明,且在文章页面给出原文连接,否则保留追究法律责任的权利。