From f29aa6c8934ad995b375085de37e23e72f918ea6 Mon Sep 17 00:00:00 2001 From: nova1751 Date: Sun, 25 Aug 2024 01:14:44 +0800 Subject: [PATCH] perf: optimize the performance when the cursor is still --- package.json | 1 + pnpm-lock.yaml | 4 ++++ src/utils/cursor.js | 19 ++++++++++++++----- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 392e21ca1..537502637 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 148eb7541..ea2a47d48 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: fetch-jsonp: specifier: ^1.3.0 version: 1.3.0 + lodash-es: + specifier: ^4.17.21 + version: 4.17.21 pinia: specifier: ^2.1.7 version: 2.1.7(vue@3.4.24) @@ -2405,6 +2408,7 @@ packages: workbox-google-analytics@6.6.0: resolution: {integrity: sha512-p4DJa6OldXWd6M9zRl0H6vB9lkrmqYFkRQ2xEiNdBFp9U0LhsGO7hsBscVEyH9H2/3eZZt8c97NB2FD9U2NJ+Q==} + deprecated: It is not compatible with newer versions of GA starting with v4, as long as you are using GAv3 it should be ok, but the package is not longer being maintained workbox-navigation-preload@6.6.0: resolution: {integrity: sha512-utNEWG+uOfXdaZmvhshrh7KzhDu/1iMHyQOV6Aqup8Mm78D286ugu5k9MFD9SzBT5TcwgwSORVvInaXWbvKz9Q==} diff --git a/src/utils/cursor.js b/src/utils/cursor.js index 49f858c47..8fce9a76b 100644 --- a/src/utils/cursor.js +++ b/src/utils/cursor.js @@ -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 { @@ -49,7 +56,6 @@ class Cursor { document.body.appendChild((this.scr = document.createElement("style"))); this.scr.innerHTML = `* {cursor: url("data:image/svg+xml,") 4 4, auto !important}`; } - refresh() { this.scr.remove(); this.cursor.classList.remove("active"); @@ -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"); @@ -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()); + } } }