Skip to content

Commit

Permalink
Stage3: Smooth Animation on stop click is achieved. (though not expec…
Browse files Browse the repository at this point in the history
…ted result)

Even after stopping animation frame request will go on. But on unmount frame request are cancelled
  • Loading branch information
A M Akankshit authored and A M Akankshit committed Oct 30, 2020
1 parent ed438b5 commit 89669d9
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions src/confetti/index.js
Expand Up @@ -31,9 +31,11 @@ const Confetti = ({ playAnimation = false, styles = {} }) => {
let width;

const updateAndDrawParticles = (context) => {
let stopStremingConfetti = !playAnimation;
waveAngle = waveAngle + 0.01;
let x2, y2;
for (let particle of particles) {
for (let i = 0; i < particles.length; i++) {
const particle = particles[i];
//update particle
particle.tiltAngle += particle.tiltAngleIncrement;
particle.x = particle.x + Math.sin(particle.tiltAngle) * 2 - 1;
Expand All @@ -42,8 +44,13 @@ const Confetti = ({ playAnimation = false, styles = {} }) => {
(Math.cos(waveAngle) + particle.diameter + confetti.speed) * 0.2;
particle.tilt = Math.sin(particle.tiltAngle);
if (particle.x > width + 20 || particle.x < -20 || particle.y > height) {
setParticle(particle);
particle.y = -20;
if (stopStremingConfetti) {
particle.y = -20;
particles.splice(i, 1);
} else {
setParticle(particle);
particle.y = -20;
}
}
//draw particle
context.beginPath();
Expand Down Expand Up @@ -88,23 +95,22 @@ const Confetti = ({ playAnimation = false, styles = {} }) => {
};

useEffect(() => {
if (playAnimation === true) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
const { width, height } = canvas.getBoundingClientRect();
if (canvas.width !== width || canvas.height !== height) {
const { devicePixelRatio: ratio = 1 } = globalThis;
/**
* In case the device pixel ratio is more, the particles will be pixelated and will semm blur.
* That's why we are resizing the canvas.
* */
canvas.width = width * ratio;
canvas.height = height * ratio;
count = parseInt(canvas.width / 10, 10);
context.scale(ratio, ratio);
}
startAnimation(context);
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
const { width, height } = canvas.getBoundingClientRect();
if (canvas.width !== width || canvas.height !== height) {
const { devicePixelRatio: ratio = 1 } = globalThis;
/**
* In case the device pixel ratio is more, the particles will be pixelated and will semm blur.
* That's why we are resizing the canvas.
* */
canvas.width = width * ratio;
canvas.height = height * ratio;
count = parseInt(canvas.width / 10, 10);
context.scale(ratio, ratio);
}
startAnimation(context);

return () => {
cancelAnimationFrame(animationId);
};
Expand Down

0 comments on commit 89669d9

Please sign in to comment.