Infinite Loop Confetti Loop - javascript

I have created a fancy confetti animation but it seems to run infinitely. I only want it to run for a few seconds and stop gracefully. This is my first time working with requestAnimationFrame so I would not know where to stop the animation. I have tried to use a simple counter variable around the update but I have noticed that I have to multiply potential endless loops that will still run in the background eating resources. This snippet of code does not seem to fully stop all the functions from running in a never-ending loop.
let timer = 0;
const drawConfetti = () => {
ctx.clearRect(0, 0, wW, wH);
timer++;
confetties.forEach(confetti => {
if (timer < 1500){
confetti.update();
}else{
return
}
});
requestAnimationFrame(drawConfetti);
I have updated the code below to the first answer suggested but now the animation is stops mid rendering now.
const AMOUNT = 150;
const INTERVAL = 300;
const COLORS = ['#4579FF', '#29EAFC', '#FAB1C0', '#50E3C2', '#FFFC9D', '#1A04B3', '#F81C4D'];
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const wW = window.innerWidth;
const wH = window.innerHeight;
const random = (min, max) => {
return Math.random() * (max - min) + min;
};
const randomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};
const confetties = [];
class Confetti {
constructor(width, height, color, speed, x, y, rotation) {
this.width = width;
this.height = height;
this.color = color;
this.speed = speed;
this.x = x;
this.y = y;
this.rotation = rotation;
}
update() {
const y = this.y < wH ? this.y += this.speed : -20;
const x = this.x + Math.sin(this.y * (this.speed / 100));
this.x = x > wW ? 0 : x;
this.y = y;
ctx.fillStyle = this.color;
ctx.save();
ctx.translate(x + (this.width / 2), y + (this.height / 2));
ctx.rotate((y * this.speed) * Math.PI / 180);
ctx.scale(Math.cos(y / 10), 1);
ctx.fillRect(-this.width / 2, -this.height / 2,
this.width,
this.height
);
ctx.restore();
}
}
canvas.width = wW;
canvas.height = wH;
let animationId;
const drawConfetti = () => {
ctx.clearRect(0, 0, wW, wH);
confetties.forEach(confetti => {
confetti.update();
});
animationId = requestAnimationFrame(drawConfetti);
}
const renderConfetti = () => {
let count = 0;
let stagger = setInterval(() => {
if (count < AMOUNT) {
const x = random(0, wW);
const speed = random(1.0, 2.0);
const width = 24 / speed;
const height = 48 / speed;
const color = COLORS[randomInt(0, COLORS.length)];
const confetti = new Confetti(width, height, color, speed, x, -20, 0);
confetties.push(confetti);
} else {
clearInterval(stagger);
}
count++;
}, INTERVAL);
drawConfetti();
}
renderConfetti();
function stop() {
cancelAnimationFrame(animationId)
}
setTimeout(stop, 5000);
body {
margin: 0;
background-color: #000;
}
<canvas id="canvas"></canvas>

The requestAnimationFrame funciton is being called recursively. If you want to stop it, you should use cancelAnimationFrame. To do this, save the ID of the animation outside of the drawLoop function.
e.g
let animationId;
const drawConfetti = () => {
ctx.clearRect(0, 0, wW, wH);
confetties.forEach(confetti => {
confetti.update();
});
animationId = requestAnimationFrame(drawConfetti);
}
// now cancel whenever you want
cancelAnimationFrame(animationId)

Related

How to implement object rotation animation?

There is a falling balls code https://jsfiddle.net/d1e8x7wk/,
which is generated using canvas
Code also added to this editor
window.addEventListener('load', () => {
//---------------------------------------
// Set up ball options
//---------------------------------------
const imgBalls = [
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png',
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png',
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png',
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png',
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png',
'https://cdn.iconscout.com/icon/premium/png-256-thumb/basketball-2500972-2093649.png'
]
let ballCount = imgBalls.length, // How many balls
DAMPING = 0.4, // Damping
GRAVITY = 0.01, // Gravity strength
SPEED = 5, // Ball speed
ballAdditionTime = 100, // How fast are balls added
ballSrc = imgBalls, // Ball image source
topOffset = 400, // Adjust this for initial ball spawn point
xOffset = 0, // left offset
yOffset = 0, // bottom offset
ballDensity = 20, // How dense are the balls
ball_1_size = 200, // Ball 1 size
ball_2_size = 180, // Ball 2 size
ball_3_size = 62, // Ball 6 size
canvasWidth = 1500, // Canvas width
canvasHeight = 1000, // Canvas height
stackBall = true, // Stack the balls (or false is overlap)
ballsLoaded = 0,
stopAnimation = false;
//---------------------------------------
// Canvas globals
//---------------------------------------
let canvas,
ctx,
TWO_PI = Math.PI * 2,
balls = [],
vel_x,
vel_y;
let rect = {
x: 0,
y: 0,
w: canvasWidth,
h: canvasHeight
};
//---------------------------------------
// do the animation
//---------------------------------------
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, ballAdditionTime);
};
//---------------------------------------
// set up the ball
//---------------------------------------
const Ball = function(x, y, radius, num) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.fx = 0;
this.fy = 0;
this.radius = radius;
this.num = num;
this.angle = 0;
// Different ball sizes
let random = Math.round(Math.random() * imgBalls.length)
if (random === 0) {
this.width = ball_1_size;
this.height = ball_1_size;
if (stackBall) {
this.radius = ball_1_size / 2;
}
} else if (random === 1 || random === 2) {
this.width = ball_2_size;
this.height = ball_2_size;
if (stackBall) {
this.radius = ball_2_size / 2;
}
} else {
this.width = ball_3_size;
this.height = ball_3_size;
if (stackBall) {
this.radius = ball_3_size / 2;
}
}
ctx.rotate(this.angle * Math.PI / 180);
};
//---------------------------------------
// Apply the physics
//---------------------------------------
Ball.prototype.apply_force = function(delta) {
delta *= delta;
this.fy += GRAVITY;
this.x += this.fx * delta;
this.y += this.fy * delta;
this.fx = this.fy = 0;
};
//---------------------------------------
// Newtonian motion algorithm
//---------------------------------------
Ball.prototype.velocity = function() {
var nx = this.x * 2 - this.px;
var ny = this.y * 2 - this.py;
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
};
//---------------------------------------
// Ball prototype
//---------------------------------------
Ball.prototype.draw = function(ctx) {
img = new Image();
img.src = imgBalls[this.num];
if (stackBall) {
ctx.drawImage(
img,
this.x - this.radius - xOffset,
this.y - this.radius - xOffset,
this.width,
this.height
);
} else {
ctx.drawImage(
img,
this.x - xOffset,
this.y - yOffset,
this.width,
this.height
);
}
};
//---------------------------------------
// resolve collisions (ball on ball)
//---------------------------------------
let resolve_collisions = function(ip) {
let i = balls.length;
while (i--) {
let ball_1 = balls[i];
let n = balls.length;
while (n--) {
if (n == i) continue;
let ball_2 = balls[n];
let diff_x = ball_1.x - ball_2.x;
let diff_y = ball_1.y - ball_2.y;
let length = diff_x * diff_x + diff_y * diff_y;
let dist = Math.sqrt(length);
let real_dist = dist - (ball_1.radius + ball_2.radius);
if (real_dist < 0) {
let vel_x1 = ball_1.x - ball_1.px;
let vel_y1 = ball_1.y - ball_1.py;
let vel_x2 = ball_2.x - ball_2.px;
let vel_y2 = ball_2.y - ball_2.py;
let depth_x = diff_x * (real_dist / dist);
let depth_y = diff_y * (real_dist / dist);
ball_1.x -= depth_x * 0.5;
ball_1.y -= depth_y * 0.5;
ball_2.x += depth_x * 0.5;
ball_2.y += depth_y * 0.5;
if (ip) {
let pr1 = (DAMPING * (diff_x * vel_x1 + diff_y * vel_y1)) / length;
let pr2 = (DAMPING * (diff_x * vel_x2 + diff_y * vel_y2)) / length;
vel_x1 += pr2 * diff_x - pr1 * diff_x;
vel_x2 += pr1 * diff_x - pr2 * diff_x;
vel_y1 += pr2 * diff_y - pr1 * diff_y;
vel_y2 += pr1 * diff_y - pr2 * diff_y;
ball_1.px = ball_1.x - vel_x1;
ball_1.py = ball_1.y - vel_y1;
ball_2.px = ball_2.x - vel_x2;
ball_2.py = ball_2.y - vel_y2;
}
}
}
}
};
//---------------------------------------
// Bounce off the walls
//---------------------------------------
let check_walls = function() {
let i = balls.length;
while (i--) {
let ball = balls[i];
if (ball.x < ball.radius) {
let vel_x = ball.px - ball.x;
ball.x = ball.radius;
ball.px = ball.x - vel_x * DAMPING;
} else if (ball.x + ball.radius > canvas.width) {
vel_x = ball.px - ball.x;
ball.x = canvas.width - ball.radius;
ball.px = ball.x - vel_x * DAMPING;
}
// Ball is new. So don't do collision detection until it hits the canvas. (with an offset to stop it snapping)
if (ball.y > 100) {
if (ball.y < ball.radius) {
let vel_y = ball.py - ball.y;
ball.y = ball.radius;
ball.py = ball.y - vel_y * DAMPING;
} else if (ball.y + ball.radius > canvas.height) {
vel_y = ball.py - ball.y;
ball.y = canvas.height - ball.radius;
ball.py = ball.y - vel_y * DAMPING;
}
}
}
};
//---------------------------------------
// Add a ball to the canvas
//---------------------------------------
let add_ball = function(num) {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
let r = 30 + Math.random() * ballDensity;
let diff_x = x;
let diff_y = y;
let dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
balls.push(new Ball(x, y, r, num));
};
//---------------------------------------
// iterate balls
//---------------------------------------
let update = function() {
let iter = 1;
let delta = SPEED / iter;
while (iter--) {
let i = balls.length;
while (i--) {
balls[i].apply_force(delta);
balls[i].velocity();
}
resolve_collisions();
check_walls();
i = balls.length;
while (i--) {
balls[i].velocity();
let ball = balls[i];
}
resolve_collisions();
check_walls();
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
i = balls.length;
while (i--) {
balls[i].draw(ctx);
}
requestAnimFrame(update);
};
//---------------------------------------
// Set up the canvas object
//---------------------------------------
function doBalls() {
stopAnimation = false;
canvas = document.getElementById("balls");
ctx = canvas.getContext("2d");
let $canvasDiv = document.querySelector(".section");
function respondCanvas() {
canvas.height = $canvasDiv.clientHeight;
canvas.width = $canvasDiv.clientWidth;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
respondCanvas();
ballAdd();
}
function ballAdd() {
let count = 0;
let timer = setInterval(function() {
addBallTimer();
}, 100);
let addBallTimer = function() {
add_ball(count % ballCount);
count++;
if (count === ballCount) {
stopTimer();
}
};
let stopTimer = function() {
clearInterval(timer);
};
update();
}
doBalls();
});
.section {
position: relative;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #000;
}
<div class="section">
<canvas id="balls"></canvas>
</div>
I'm trying to make a rotation the balls
const Ball = function(x, y, radius, num) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.fx = 0;
this.fy = 0;
this.radius = radius;
this.num = num;
this.angle = 0;
// Different ball sizes
let random = Math.round(Math.random() * imgBalls.length)
if (random === 0) {
this.width = ball_1_size;
this.height = ball_1_size;
if (stackBall) {
this.radius = ball_1_size / 2;
}
} else if (random === 1 || random === 2) {
this.width = ball_2_size;
this.height = ball_2_size;
if (stackBall) {
this.radius = ball_2_size / 2;
}
} else {
this.width = ball_3_size;
this.height = ball_3_size;
if (stackBall) {
this.radius = ball_3_size / 2;
}
}
ctx.rotate(this.angle * Math.PI / 180);
};
After reading the information,
I wrote this code, but it does not work for me
ctx.rotate(this.angle * Math.PI / 180);
I must have misunderstood how to do this, tell me how to properly rotate the balls
Thanks in advance
You will need to
increase the angle at some point in your code
apply a rotation transform to rotate around each ball center before each drawImage call
ctx.save();
ctx.translate(+this.x, +this.y);
ctx.rotate(this.angle++ * Math.PI / 180);
ctx.translate(-this.x, -this.y);
ctx.drawImage
ctx.restore()
ctx.save() and ctx.restore() is called to restore the canvas transform after each draw call.
Please read
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rotate#rotating_a_shape_around_its_center
for details on applying transforms to Canvas.

JavaScript Canvas moving and animating color at the same time

My script is animating the changing of the color of the ball. The 1 complete sequence takes 1 second and changes the color from green to blue using gradient. I am trying to add a move() method to move the ball.
However I have a problem where to execute my move() method.
Right now the animation of the ball moving is executed witihin the animation of the color but it shouldn't be. The color should change diffrently and the ball should be moving ininitely. I want the ball to move infinitely and the chaning of the color has to take 1 second like it is now.
Am I doing this right?
<-- Edit - I changed interval to 2000ms, just to visualize the problem better ( the moving of the ball stops but it shouldn't)
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var i = 0;
var ec;
var direction = 0;
var x = 100;
var dx = 10;
var y = 100;
var radius = 100;
function move() {
if(x + radius > window.innerWidth || x - radius < 0) {
dx = -dx;
}
x += dx;
}
function animate() {
c.clearRect(0, 0, innerWidth, innerHeight)
move();
var gradient = c.createLinearGradient(0, 0, 170, 0);
ec = 255 - i;
gradient.addColorStop(1, "rgba(" + 0 + "," + i + "," + ec + ")", 1);
c.fillStyle = gradient;
c.beginPath();
c.arc(x, y, radius, 0, 2 * Math.PI);
c.fill();
console.log(i, ec);
if(i == 255) direction = 1;
if(direction == 1 && i == 0) direction = 2;
if(direction == 0 ) i+=5;
else if(direction == 1 && direction != 2) i -= 5;
if(direction != 2) requestAnimationFrame(animate);
}
setInterval(function draw() {
direction = 0;
animate();
}, 2000);
canvas {
border: 1px solid black;
}
body {
margin: 0;
}
<canvas></canvas>
I got everything working as desired. But it was complicated, is there any way to make it simpler?
Could someone teach me how to use snippet?
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var i = 0;
var ec;
var direction = 0;
var x = 300;
var y = 300;
var radius = 200;
var speed = 5;
var dateDiff;
var date1;
var executedTimer = false;
var executedColor = false;
function draw() {
c.clearRect(0, 0, innerWidth, innerHeight)
c.beginPath();
c.arc(x, y, radius, 0, 2 * Math.PI);
c.fill();
}
function move() {
if(x + radius > window.innerWidth || x - radius < 0) {
speed = -speed;
}
x += speed;
}
function color() {
var gradient = c.createLinearGradient(0, 0, 170, 0);
ec = 255 - i;
gradient.addColorStop(1, "rgba(" + 0 + "," + i + "," + ec + ")", 1);
c.fillStyle = gradient;
//console.log(i, ec);
if(i == 255) direction = 1;
if(direction == 1 && i == 0) direction = 2;
if(direction == 0 ) i += 5;
else if(direction == 1 && direction != 2) i -= 5;
}
function timerStart() {
date1 = new Date();
executedTimer = true;
}
function timerCheck() {
var date2 = new Date();
dateDiff = Math.abs(date1 - date2);
if(dateDiff >= 1000)date1 = date2;
}
function animate() {
draw();
move();
if(executedTimer == false) timerStart();
if(executedColor == false) {
executedColor = true;
color();
}
if(dateDiff < 1000) color();
if(dateDiff >= 1000 && direction == 2) {
i = 0;
direction = 0;
//console.log(dateDiff);
color();
}
timerCheck();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
border: 1px solid black;
}
body {
margin: 0;
}
<canvas></canvas>
Treat both the position and the color as two different components, each with its own duration and its update method.
Then start a single animation loop in which you will
update the color component
update the position component
draw the scene
To ensure your animations last the duration you want, use a delta-time, which will let you know where you are relatively to the beginning of the animation.
This avoids issues with monitor using different refresh-rates (simply incrementing a value by a fixed amount will make your objects move twice faster on a 120Hz monitor than on a 60Hz one, generally not what you want), and it also allows to not care about the fact your animation is being paused by the browser when offscreen.
{
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const w = canvas.width = window.innerWidth;
const h = canvas.height = window.innerHeight;
const radius = Math.min( w, h ) / 3;
const color = {
duration: 1000,
update( elapsed ) {
const delta = (elapsed % this.duration) / this.duration;
const direction = (elapsed % (this.duration * 2)) - this.duration;
const val = (direction < 0) ?
255 - (delta * 255) :
delta * 255 ;
this.val = `rgba(0, ${ val }, ${ 255 - val })`;
}
};
const position = {
duration: 3000,
y: h / 2,
update( elapsed ) {
const delta = (elapsed % this.duration) / this.duration;
const direction = (elapsed % (this.duration * 2)) - this.duration;
this.x = direction < 0 ?
delta * w :
w - (delta * w);
}
};
function draw() {
ctx.clearRect( 0, 0, w, h );
ctx.beginPath();
ctx.arc( position.x, position.y, radius, 0, Math.PI *2 );
ctx.fillStyle = color.val;
ctx.fill();
}
// We record the time we started the animation
// We will base our time relative animation on that
const start = performance.now();
function anim( timestamp ) {
const elapsed = timestamp - start;
color.update( elapsed );
position.update( elapsed );
draw();
requestAnimationFrame( anim );
}
requestAnimationFrame( anim );
}
body {
margin: 0;
}
<canvas></canvas>
And of course if you are going to have a lot of such both-directions animations, you could write an helper function to just get the value based on the elapsed time:
{
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const w = canvas.width = window.innerWidth;
const h = canvas.height = window.innerHeight;
const radius = Math.min( w, h ) / 3;
function getValueAtTime( elapsed, duration, max_val ) {
const delta = (elapsed % duration) / duration;
const direction = (elapsed % (duration * 2)) - duration;
const val = delta * max_val;
return direction < 0 ? val : max_val - val;
}
const color = {
duration: 1000,
update( elapsed ) {
const val = getValueAtTime( elapsed, this.duration, 255 );
this.val = `rgba(0, ${ val }, ${ 255 - val })`;
}
};
const position = {
duration: 3000,
y: h / 2,
update( elapsed ) {
this.x = getValueAtTime( elapsed, this.duration, w );
}
};
function draw() {
ctx.clearRect( 0, 0, w, h );
ctx.beginPath();
ctx.arc( position.x, position.y, radius, 0, Math.PI *2 );
ctx.fillStyle = color.val;
ctx.fill();
}
// We record the time we started the animation
// We will base our time relative animation on that
const start = performance.now();
function anim( timestamp ) {
const elapsed = timestamp - start;
color.update( elapsed );
position.update( elapsed );
draw();
requestAnimationFrame( anim );
}
requestAnimationFrame( anim );
}
body {
margin: 0;
}
<canvas></canvas>

How do I get this canvas animation script to work in Firefox?

I wrote this canvas animation script in hopes to use it on my portfolio website, but it is basically non-functional in Firefox, and I am not sure why. The script draws stars on the canvas that slowly rotate, and if you hold down the mouse button they spin faster creating trails. It works awesome in chrome, but is extremely slow and choppy in Firefox.
let canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let mouse = {
x: window.innerWidth / 2,
y: window.innerHeight / 2
}
let stars = [];
const starCount = 800;
class Star {
constructor(x, y, radius, color){
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = () => {
c.save();
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.shadowColor = this.color;
c.shadowBlur = 15;
c.fill();
c.closePath();
c.restore();
};
this.update = () => {
this.draw();
};
}
}
let colors = [
"#A751CC",
"#DE9AF9",
"#F9E0F9",
"#B5ECFB",
"#5F86F7"
];
(initializeStars = () =>{
for(let i = 0; i < starCount; i++){
let randomColorIndex = Math.floor(Math.random() * 5);
let randomRadius = Math.random() * 2;
let x = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2;
let y = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2;
stars.push(new Star(x, y, randomRadius, colors[randomColorIndex]));
}
})();
let opacity = 1;
let speed = 0.0005;
let time = 0;
let spinSpeed = desiredSpeed => {
speed += (desiredSpeed - speed) * 0.01;
time += speed;
return time;
}
let starOpacity = (desiredOpacity, ease) => {
opacity += (desiredOpacity - opacity) * ease;
return c.fillStyle = `rgba(18, 18, 18, ${opacity})`;
}
let animate = () => {
window.requestAnimationFrame(animate);
c.save();
if(mouseDown){
starOpacity(0.01, 0.03);
spinSpeed(0.012);
}else{
starOpacity(1, 0.01);
spinSpeed(0.001);
}
c.fillRect(0,0, canvas.width, canvas.height);
c.translate(canvas.width / 2, canvas.height / 2);
c.rotate(time);
for(let i = 0; i < stars.length; i++){
stars[i].update();
}
c.restore();
}
window.addEventListener('mousemove', e => {
mouse.x = e.clientX - canvas.width / 2;
mouse.y = e.clientY - canvas.height / 2;
});
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
stars = [];
initializeStars();
});
let mouseDown = false;
window.addEventListener("mousedown", () =>{
mouseDown = true;
});
window.addEventListener("mouseup", () => {
mouseDown = false;
});
animate();
Here is the link to the demo on Code Pen; any help is appreciated.
You can use rect instead of arc to draw your stars:
c.rect(this.x, this.y, 2*this.radius, 2*this.radius);
remove the blur It's extremely expensive:
//c.shadowBlur = 15;
You can use a radial gradient going from opaque in the center to transparent in his stead.

Using HTML5 Canvas to Simulate Firework Explosion

I am currently trying to learn JavaScript and am experimenting with canvas animation. I tried to create firework effect using canvas. I am using this source as a reference.
So far, I have successfully created a single particle and let it shoot to the sky. However, I couldn't let it explode...
Is there something wrong with my code and logic? I would be really appreciate if someone could kindly look into my code and give me some advices what should I do to correct it.
Following is my .js code:
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
let w = canvas.width;
let h = canvas.height;
w = window.innerWidth;
h = window.innerHeight;
let particles = [];
class Particle{
constructor(pos, vel, target){
// firework animation properties
this.gravity = 1;
this.alpha = 1;
this.easing = Math.random() * 0.02;
this.fade = Math.random() * 0.1;
this.pos = {
x: pos.x || 0,
y: pos.y || 0
};
this.vel = {
x: vel.x || 0,
y: vel.y || 0
};
this.target = {
y: target.y || 0
};
this.lastPos = {
x: this.pos.x,
y: this.pos.y
};
}
update(){
this.lastPos.x = this.pos.x;
this.lastPos.y = this.pos.y;
this.vel.y += this.gravity;
this.pos.y += this.vel.y;
this.alpha -= this.fade;
this.distance = (this.target.y - this.pos.y);
// ease the position
this.pos.y += this.distance * (0.03 + this.easing);
// cap to 1
this.alpha = Math.min(this.distance * this.distance * 0.00005, 1);
this.pos.x += this.vel.x;
return (this.alpha < 0.005);
}
draw(){
let x = Math.round(this.pos.x),
y = Math.round(this.pos.y),
xVel = (x - this.lastPos.x) * -5,
yVel = (y - this.lastPos.y) * -5;
context.fillStyle = "rgba(255,255,255,0.3)";
context.beginPath();
context.moveTo(this.pos.x, this.pos.y);
context.lineTo(this.pos.x + 1.5, this.pos.y);
context.lineTo(this.pos.x + xVel, this.pos.y + yVel);
context.lineTo(this.pos.x - 1.5, this.pos.y);
context.closePath();
context.fill();
}
}
const init = () =>{
// set canvas size to window size
onResize();
document.addEventListener('mouseup', createParticle, true);
// set off fireworks
update();
}
const update = () =>{
// clear up the canvas
clearCanvas();
// start the animation loop
requestAnimFrame(update);
createFireworks();
}
const createFireworks = () =>{
for(let i = 0; i < particles.length; i++){
if(particles[i].update()){
// kill off the firework, replace it
// with the particles for the exploded version
particles.splice(particles.length, 1);
explodeFireworks(particles[i]);
}
particles[i].draw();
}
console.log(particles.length);
}
const explodeFireworks = (firework) =>{
let count = 100;
let angle = (Math.PI * 2) / count;
for(let i = 0; i < count; i++){
let randomVelocity = 4 + Math.random() * 4;
let particleAngle = count * angle;
createParticle(
firework.pos,
{
x: Math.cos(particleAngle) * randomVelocity,
y: Math.sin(particleAngle) * randomVelocity
},
null
);
}
}
//without parameters create particle, with parameters create firework
const createParticle = (pos, vel, target) =>{
pos = pos || {};
vel = vel || {};
target = target || {};
particles.push(
new Particle(
{
x: w/2,
y: h
},
{
x: vel.x || Math.random() * 3 - 1.5,
y: vel.y || 0
},
{
y: target.y || h/2
}
)
);
}
const clearCanvas = () =>{
context.clearRect(0,0,canvas.width, canvas.height);
}
const onResize =() => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
// Simple polyfill for browsers that don't support requestAnimationFrame
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
window.addEventListener('load', init, false);

Why does my Javascript animation slowdown after a while

So I am in the process of making this rhythm game with canvas, all that it does up to this point is render the receivers (the point the blocks are going to collide with so the user can press the corresponding buttons and get points) and it renders the dancer animation. For some reason though after the page is open for a while the dancer slows down significantly and continues to gradually slow.
I can't figure out why or how to fix it. Anyone have any ideas?
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time:0,
speed:0,
image:null,
x:0,
y:0,
currentFrame:0,
width:50,
height:100,
ready:false
}
function onload() {
spritesheet = new Image();
spritesheet.src = "danceSheet.png";
spritesheet.onload = initiate;
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime:0,
currentTime:0,
receivers:[],
senders:[],
lanes:[],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height );
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for(initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
}
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if(dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if(dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
game.receivers.forEach( function(receiver) {
ctx.rect(receiver.x,receiver.y,receiver.width,receiver.height);
ctx.fillStyle = "red";
ctx.fill();
}
)
}
function main() {
update();
render();
requestAnimationFrame(main);
}
I'm trying to get an idea of the slowness you're seeing so I adjusted your code to get a frames-per-second. Haven't found the cause yet for the drop.
Update
I found that the frames were dropping from drawing the rectangles. I've altered the code to use fillRect put the fill style outside of the loop. This seems to have fixed the frame drop.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time: 0,
speed: 0,
image: null,
x: 0,
y: 0,
currentFrame: 0,
width: 50,
height: 100,
ready: false
}
function onload() {
spritesheet = document.createElement('canvas');
spritesheet.width = (dancer.width * 12);
spritesheet.height = dancer.height;
var ctx = spritesheet.getContext('2d');
ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.strokeStyle = "red";
for (var i = 0; i < 12; i++) {
var x = (i * dancer.width) + 10;
ctx.fillText(i,x,60);
ctx.beginPath();
ctx.rect(i*dancer.width,0,dancer.width,dancer.height);
ctx.stroke();
}
initiate();
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime: 0,
currentTime: 0,
receivers: [],
senders: [],
lanes: [],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height);
//ctx.strokeStyle="red";
//ctx.beginPath();
//ctx.lineWidth = 3;
//ctx.rect(dancer.x,dancer.y,dancer.width,dancer.height);
//ctx.stroke();
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for (initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
};
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if (dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if (dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
ctx.fillStyle = "red";
game.receivers.forEach(function(receiver) {
ctx.fillRect(receiver.x, receiver.y, receiver.width, receiver.height);
});
ctx.fillText(fps,10,10);
}
var fps = 0;
var frames = 0;
function getFps() {
fps = frames;
frames = 0;
setTimeout(getFps,1000);
}
getFps();
function main() {
update();
render();
frames++;
requestAnimationFrame(main);
}
onload();
canvas {
border:1px solid blue;
}

Categories