Skip to content

Commit

Permalink
Merge pull request imsyy#347 from nova1751/dev
Browse files Browse the repository at this point in the history
perf: optimize the performance when the cursor is still
  • Loading branch information
imsyy authored Sep 30, 2024
2 parents 31bbcc3 + 29062f2 commit 081834c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"dayjs": "^1.11.10",
"element-plus": "^2.7.1",
"fetch-jsonp": "^1.3.0",
"lodash-es": "^4.17.21",
"pinia": "^2.1.7",
"pinia-plugin-persistedstate": "^3.2.1",
"swiper": "^11.1.1",
Expand Down
4 changes: 4 additions & 0 deletions pnpm-lock.yaml

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

19 changes: 14 additions & 5 deletions src/utils/cursor.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { isEqual } from "lodash-es";

let mainCursor;

Math.lerp = (a, b, n) => (1 - n) * a + n * b;
const lerp = (a, b, n) => {
if (Math.round(a) === b) {
return b;
}
return (1 - n) * a + n * b;
};

const getStyle = (el, attr) => {
try {
Expand Down Expand Up @@ -49,7 +56,6 @@ class Cursor {
document.body.appendChild((this.scr = document.createElement("style")));
this.scr.innerHTML = `* {cursor: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' width='10px' height='10px'><circle cx='4' cy='4' r='4' fill='white' /></svg>") 4 4, auto !important}`;
}

refresh() {
this.scr.remove();
this.cursor.classList.remove("active");
Expand All @@ -72,6 +78,7 @@ class Cursor {
y: e.clientY - 8,
};
this.cursor.classList.remove("hidden");
this.render();
};
document.onmouseenter = () => this.cursor.classList.remove("hidden");
document.onmouseleave = () => this.cursor.classList.add("hidden");
Expand All @@ -81,13 +88,15 @@ class Cursor {

render() {
if (this.pos.prev) {
this.pos.prev.x = Math.lerp(this.pos.prev.x, this.pos.curr.x, 0.35);
this.pos.prev.y = Math.lerp(this.pos.prev.y, this.pos.curr.y, 0.35);
this.pos.prev.x = lerp(this.pos.prev.x, this.pos.curr.x, 0.35);
this.pos.prev.y = lerp(this.pos.prev.y, this.pos.curr.y, 0.35);
this.move(this.pos.prev.x, this.pos.prev.y);
} else {
this.pos.prev = this.pos.curr;
}
requestAnimationFrame(() => this.render());
if (!isEqual(this.pos.curr, this.pos.prev)) {
requestAnimationFrame(() => this.render());
}
}
}

Expand Down

0 comments on commit 081834c

Please sign in to comment.