通过对弹动的原理来实现如下效果,做出一个弹球游戏,用鼠标点作为目标,所以圆球当离鼠标进的时候就会慢慢移动,远的时候就会快速移动,因为有摩擦力所以会慢慢暂停,在程序的结尾加上重力让它产生悬浮效果
var canvas = document.getElementById("canvas");
var cxt=canvas.getContext("2d");
var spring=0.01;
var targetX=canvas.width/2;
var targetY=canvas.height/2;
var vx=0;
var vy=0;
var gravity=0.5;
function Ball(x,y,radius,speed){
this.x=x;
this.y=y;
this.radius=radius;
this.speed=speed;
}
var balles=[];
balles.push(new Ball(20,20,15,{x:0,y:0}));
var b=balles[0];
var friction=0.95;
function downball(){
var dx=targetX-b.x;
var dy=targetY-b.y
vx=dx*spring;
b.speed.x+=vx;
b.speed.x*=friction;
b.x+=b.speed.x;
vy=dy*spring+gravity;
b.speed.y+=vy;
b.speed.y*=friction;
b.y+=b.speed.y;
cxt.clearRect(0,0,canvas.width,canvas.height);
cxt.beginPath();
cxt.strokeStyle="#fff";
cxt.moveTo(b.x,b.y);
cxt.lineTo(targetX,targetY);
cxt.stroke();
cxt.closePath();
cxt.beginPath();
cxt.fillStyle="#fff";
cxt.arc(b.x,b.y,b.radius,0,Math.PI*2,true);
cxt.fill();
cxt.closePath();
canvasId = requestAnimationFrame(downball)
// if(Math.abs(b.speed.x)<0.001)
// cancelAnimationFrame(canvasId);
}
var canvasId;
downball();
function move(event){
targetX=event.point.x;
targetY=event.point.y;
}
function up(event){}
function down(event){}
tool.MT(canvas,move,down,up);