Last lesson I learned the relative to the mouse as the target point of the elastic motion, this time to learn how the above a ball as the target point of the elastic motion, this time the function is more complex, first divided into the following several functions, the first definition of a ball model, after the addition of 4 balls, in the load called the animation event, After the animation event loaded in the line of events, after the line to draw the ball, and specifically with a function to calculate, that is, completely separate the hierarchy, so as to avoid their own logical thinking confusion, this is a good programming thinking, partition processing content, so effectively avoid code reuse, but also increased code readability.
Or as before, the code is as follows:
var canvas = document.getElementById ("Canvas");
var Cxt=canvas.getcontext ("2d");
var moves={x:0,y:0}
var balles=[];
var spring=0.03;
var g=6;
var force=0.85
var friction=0.1;
function Ball (x,y,radius,speed) {
This.x=x;
This.y=y;
This.radius=radius;
this.vx=0;
this.vy=0;
This.speed=speed;
}
function Move (event) {
Moves.x=event.point.x;
Moves.y=event.point.y;
}
Function down (event) {}
function up (event) {}
function animation () {
Cxt.clearrect (0,0,canvas.width,canvas.height);
Balles.foreach (Draw);
Requestanimationframe (animation);
}
function Draw (ball,i) {
Console.log (ball);
Cxt.beginpath ();
Cxt.moveto (BALL.X,BALL.Y);
if (i!=0)
{
var b=balles[i-1];
}
Else
{
var b={x:moves.x,y:moves.y}
}
Cxt.lineto (B.X,B.Y);
Cxt.strokestyle= "Red";
Cxt.stroke ();
Cxt.closepath ();
if (i==0)
Balldraw (BALL,MOVES.X,MOVES.Y);
Else
Balldraw (BALL,BALLES[I-1].X,BALLES[I-1].Y);
}
function Balldraw (ball,targetx,targety) {
Cxt.beginpath ();
var dx=targetx-ball.x;
var dy=targety-ball.y;
var vx=dx*spring;
var vy=dy*spring;
BALL.SPEED.X+=VX;
Ball.speed.y+=vy;
Ball.speed.x*=force;
Ball.speed.y*=force;
ball.x+=ball.speed.x;
Ball.y+=ball.speed.y+g;
Cxt.arc (ball.x,ball.y,ball.radius,0,math.pi*2,true);
Cxt.fillstyle= "Red";
Cxt.fill ();
Cxt.closepath ();
}
Window.onload=function () {
for (Var i=0;i<4;i++)
{
Balles.push (New ball (20,i*50,10,{x:0,y:0}));
}
Animation ();
TOOL.MT (Canvas,move,down,up);
}
Canvas Chain-Elastic motion