Skip to content

Commit

Permalink
Controlled canvas animation on scroll
Browse files Browse the repository at this point in the history
  • Loading branch information
hackerhgl committed Jul 11, 2021
1 parent 60bcc63 commit 9f808f4
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
2 changes: 1 addition & 1 deletion build/script.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 19 additions & 6 deletions src/scripts/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as engine from "./particles";

let animationNo = undefined;
const header = document.getElementById("header");
let grid;

(function () {
const c = engine.canvas();
Expand All @@ -21,9 +22,8 @@ const header = document.getElementById("header");
const c = engine.canvas();
const ctx = canvas.getContext("2d");
ctx.translate(c.width / 2, c.height / 2);
const dimensions = engine.getDimensions();
const grid = engine.grid3d(c);
loop(grid, ctx, c, dimensions);
grid = engine.grid3d(c);
loop(ctx, c);

window.addEventListener("mousemove", function mouseMove(e) {
const c = engine.canvas();
Expand All @@ -35,13 +35,13 @@ const header = document.getElementById("header");
}
})();

function loop(grid, ctx, c, d) {
function loop(ctx, c) {
ctx.clearRect(-c.width * 0.5, -c.height * 0.5, c.width * 2, c.height * 2);
grid.forEach((particle) => {
particle.update(c, ctx, d);
particle.update(c, ctx);
});

animationNo = requestAnimationFrame(() => loop(grid, ctx, c, d));
animationNo = requestAnimationFrame(() => loop(ctx, c));
}

function getScrollbarWidth() {
Expand Down Expand Up @@ -113,4 +113,17 @@ window.onscroll = function () {
}

engine.setVelocity(speed);

const threshold = document.getElementById('contact').offsetTop;
// const scroll = h.clientHeight + parallax;
if (window.scrollY >= threshold && animationNo != null) {
cancelAnimationFrame(animationNo);
animationNo = null;
}
if (window.scrollY < threshold && animationNo == null) {
const c = engine.canvas();
const ctx = c.getContext('2d');
loop(ctx, c);
}

};
2 changes: 1 addition & 1 deletion src/scripts/particles.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function particleObject(c) {
y: 0,
size: 0,
z: 0,
update: function update(c, ctx, d) {
update: function update(c, ctx) {
particle.z -= velocity;
if (particle.z < MIN_Z) {
particle.init(true);
Expand Down

0 comments on commit 9f808f4

Please sign in to comment.