canvas弹动效果

弹动效果,用物体与目标的距离乘上系数再累加至速度上,让物体呈加速度运动,再让速度乘与摩擦力系数,让物体最终停止运动

代码如下所示

var canvas = document.getElementById("canvas");
var cxt=canvas.getContext("2d");
var spring=0.1;
var targetX=canvas.width/2;
var targetY=canvas.height/2;
var vx=0;
var vy=0;
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,20,{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
b.speed.y+=vy;
b.speed.y*=friction;
b.y+=b.speed.y;
console.log(targetX-b.x)
cxt.beginPath();
cxt.clearRect(0,0,canvas.width,canvas.height);
cxt.fillStyle="red";
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();

上一篇:【Pthreads】Pipeline Model(Assembly Line)示例


下一篇:11 Go 1.11 Release Notes