MCPcopy Index your code
hub / github.com/Vishal-raj-1/Awesome-JavaScript-Projects / animate

Function animate

assets/js/BouncingBalls.js:85–142  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

83
84// Function to give animations to the balls so that they will look like bouncing.
85function animate() {
86
87 // checking if canvas height/width is equal to the window's height/width
88 if (tx != window.innerWidth || ty != window.innerHeight) {
89 tx = window.innerWidth;
90 ty = window.innerHeight;
91 canvas.width = tx;
92 canvas.height = ty;
93 }
94
95 // it tells the browser that you want to do some animations using a callback function as an argument in it
96 requestAnimationFrame(animate);
97
98 // it sets the pixels in a rectangular area to transparent black
99 c.clearRect(0, 0, tx, ty);
100
101 // again going through each and every ball and changing its properties.
102 for (let i = 0; i < bal.length; i++) {
103
104 // update function is used to update each and every balls by changing values of their properties.
105 bal[i].update();
106
107 // translation in y direction.
108 bal[i].y += bal[i].dy;
109
110 // translation in x direction.
111 bal[i].x += bal[i].dx;
112
113 // if ball exceedes the total canvas height then translate it in upward direction with some gravity.
114 if (bal[i].y + bal[i].radius >= ty) {
115 bal[i].dy = -bal[i].dy * grav;
116 }
117 // otherwise translate it in downward direction with some velocity.
118 else {
119 bal[i].dy += bal[i].vel;
120 }
121 // if during translation of ball either in -x or +x direction, it exceedes the canvas size, translate it in the opposite direction.
122 if (bal[i].x + bal[i].radius > tx || bal[i].x - bal[i].radius < 0) {
123 bal[i].dx = -bal[i].dx;
124 }
125
126 let distance = Math.floor(Math.sqrt(
127 Math.pow(mousex - bal[i].x, 2) + Math.pow(mousey - bal[i].y, 2)
128 ));
129
130 // increasing ball's size on mouse triggered. At max the radius of the ball should be less than 70mm.
131 if (distance < bal[i].radius && bal[i].radius < 70 ) {
132 bal[i].radius += 5;
133 }
134 else {
135 if (bal[i].radius > bal[i].startradius) {
136 bal[i].radius += -5;
137 }
138 }
139 //forloop end
140 }
141 //animation end
142}

Callers 1

BouncingBalls.jsFile · 0.70

Calls 1

updateMethod · 0.45

Tested by

no test coverage detected