本文是上一篇文章的扩展,但并不依赖上一篇文章,代码可独立运行。
欢迎,萌新提问,大神评论
前面我们已经让小球在Canvas上动起来了,现在加入三个变量来模拟重力和阻力(G,RQ,RD)。
Html内容(基本没有变化)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>这是:小球的随机运动</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="900" height="400" style="background-color: #000; border-style:solid; border-width:1px; border-color:#000" ></canvas>
<script src="Ball.js"></script>
<script>
window.onload=function(){
var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
var ball=new Ball();
//随机位置
ball.x=Math.random()*canvas.width;
ball.y=Math.random();
//随机速度
ball.vx=Math.random()*15;
ball.vy=0;
function Draw(){
context.clearRect(0,0,canvas.width,canvas.height); //清除canvas的全部内容
ball.move(ball,1,0.90,0.95); //调用小球的移动方法
ball.draw(context);//调用小球的绘制方法
}
setInterval(Draw,1000/60);//计时器
};
</script>
</body>
</html>
在调用ball.move()的时候传入了四个变量
- 小球对象(ball)
- 重力加速度(G)
- 在空中运动时的阻力加速度(RQ)
- 在地面(下边界)运动时的阻力加速度(RD)
ball.js的内容
function Ball (radius,color){
if(radius === undefined){radius=40;}
if(color === undefined){color="#ff0000";}
this.x=0;//x轴坐标
this.y=0;//y轴坐标
this.radius=radius;//半径
this.vx = 0;
this.vy = 0;
this.rotation=0;//旋转角度
this.color=color;//utils.parseColor(color);
this.lineWidth=1;
this.bounce=-1; //速度取反
}
Ball.prototype.draw=function(context){
context.save();//先保存一下当前画布状态
context.translate(this.x,this.y); //将坐标原点设置为(x,y),默认
context.rotate(this.rotation); //旋转当前绘图
context.lineWidth=this.lineWidth; //画笔粗细
context.fillStyle=this.color; //圆圈内填充的颜色
context.beginPath(); //开始一条绘画路径
context.arc(0,0,this.radius,0,(Math.PI*2),true); //画一个圆
context.closePath(); //结束当前路径
context.fill(); //开始填充
//若有边框
if(this.lineWidth>0){
context.stroke(); //绘制边框
}
context.restore();//将绘图状态置为保存值。
};
//边界检测函数
Ball.prototype.checkWalls=function(ball,RD){
//右边界
if(ball.x+ball.radius>canvas.width){
ball.x=canvas.width-ball.radius;
ball.vx*=this.bounce;
}
//左边界
else if(ball.x-ball.radius<0){
ball.x=ball.radius;
ball.vx*=this.bounce;
}
//下边界
if(ball.y+ball.radius>canvas.height){
ball.y=canvas.height-ball.radius;
ball.vy*=this.bounce;
}
//上边界
else if(ball.y-ball.radius<0){
ball.y=ball.radius;
ball.vy*=this.bounce;
}
if(ball.y == canvas.height-ball.radius){
ball.vx *= RD;//在下边界运动时会受到一个地面的摩擦阻力;
}
}
//运动函数
Ball.prototype.move=function(ball,G,RQ,RD){
this.checkWalls(ball,RQ,RD);
//在空气中的摩擦阻力
this.vx*=RQ;
this.vy*=RQ;
//受到的重力
this.vy+=G;
//将速度累加到位置上
this.x+=this.vx;
this.y+=this.vy;
}
重力和空气摩擦力任何时候都有,所以写在move()中,而地面摩擦力阻力只有在接触下边界时才会产生,所以写在checkWalls()中。这一切的改变体现到代码中就是对位置变化量的变化上,即this.vx和this.vy的改变上。
动图: