Stats性能监控

在页面注入Stats.js性能监控面板

  1. // ==UserScript==
  2. // @name Stats性能监控
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.1
  5. // @description 在页面注入Stats.js性能监控面板
  6. // @author Your name
  7. // @match *://*/*
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @run-at document-end
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. /*
  15. MIT License
  16.  
  17. Copyright (c) 2024 Your name
  18.  
  19. Permission is hereby granted, free of charge, to any person obtaining a copy
  20. of this software and associated documentation files (the "Software"), to deal
  21. in the Software without restriction, including without limitation the rights
  22. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  23. copies of the Software, and to permit persons to whom the Software is
  24. furnished to do so, subject to the following conditions:
  25.  
  26. The above copyright notice and this permission notice shall be included in all
  27. copies or substantial portions of the Software.
  28.  
  29. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  30. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  32. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  33. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  34. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  35. SOFTWARE.
  36.  
  37. Based on Stats.js by mrdoob (https://github.com/mrdoob/stats.js)
  38. */
  39.  
  40. (function () {
  41. "use strict";
  42.  
  43. // 从localStorage读取设置
  44. const defaultSettings = {
  45. top: 50,
  46. left: 50,
  47. scale: 2.0,
  48. panel: 0,
  49. };
  50.  
  51. let settings = JSON.parse(localStorage.getItem("statsSettings")) || defaultSettings;
  52.  
  53. // Stats.js 代码
  54. var Stats = function () {
  55. var mode = settings.panel;
  56. var container = document.createElement("div");
  57. container.style.cssText = "position:relative;cursor:pointer;opacity:0.9;background:rgba(0,0,0,0.8);padding:0;margin:0;";
  58.  
  59. // 创建包装器
  60. const wrapper = document.createElement("div");
  61. wrapper.style.cssText = `position:fixed;top:${settings.top}px;left:${settings.left}px;z-index:999999;transform-origin:top left;transform:scale(${settings.scale});`;
  62. wrapper.appendChild(container);
  63.  
  64. // 移动功能
  65. let isDragging = false;
  66. let initialX;
  67. let initialY;
  68. let moveThreshold = 5; // 移动阈值,小于这个值认为是点击
  69. let startX;
  70. let startY;
  71.  
  72. // 防抖函数
  73. function debounce(func, wait) {
  74. let timeout;
  75. return function executedFunction(...args) {
  76. const later = () => {
  77. clearTimeout(timeout);
  78. func(...args);
  79. };
  80. clearTimeout(timeout);
  81. timeout = setTimeout(later, wait);
  82. };
  83. }
  84.  
  85. // 保存设置到localStorage
  86. const saveSettings = debounce(function () {
  87. const newSettings = {
  88. top: parseInt(wrapper.style.top),
  89. left: parseInt(wrapper.style.left),
  90. scale: parseFloat(wrapper.style.transform.replace("scale(", "").replace(")", "")),
  91. panel: mode,
  92. };
  93. localStorage.setItem("statsSettings", JSON.stringify(newSettings));
  94. }, 500);
  95.  
  96. container.addEventListener("mousedown", function (e) {
  97. if (e.target === container || e.target.tagName === "CANVAS") {
  98. isDragging = true;
  99. initialX = e.clientX - wrapper.offsetLeft;
  100. initialY = e.clientY - wrapper.offsetTop;
  101. startX = e.clientX;
  102. startY = e.clientY;
  103. wrapper.style.cursor = "move";
  104. }
  105. });
  106.  
  107. document.addEventListener("mousemove", function (e) {
  108. if (isDragging) {
  109. e.preventDefault();
  110. wrapper.style.left = e.clientX - initialX + "px";
  111. wrapper.style.top = e.clientY - initialY + "px";
  112. saveSettings();
  113. }
  114. });
  115.  
  116. document.addEventListener("mouseup", function (e) {
  117. if (isDragging) {
  118. const moveX = Math.abs(e.clientX - startX);
  119. const moveY = Math.abs(e.clientY - startY);
  120.  
  121. // 如果移动距离小于阈值,认为是点击
  122. if (moveX < moveThreshold && moveY < moveThreshold) {
  123. showPanel(++mode % container.children.length);
  124. saveSettings();
  125. }
  126. }
  127. isDragging = false;
  128. wrapper.style.cursor = "pointer";
  129. });
  130.  
  131. // 鼠标滚轮缩放
  132. let scale = settings.scale;
  133. wrapper.addEventListener("wheel", function (e) {
  134. e.preventDefault();
  135. const delta = e.deltaY > 0 ? -0.1 : 0.1;
  136. scale = Math.max(0.5, Math.min(5, scale + delta));
  137. wrapper.style.transform = `scale(${scale})`;
  138. saveSettings();
  139. });
  140.  
  141. function addPanel(panel) {
  142. container.appendChild(panel.dom);
  143. return panel;
  144. }
  145.  
  146. function showPanel(id) {
  147. for (var i = 0; i < container.children.length; i++) {
  148. container.children[i].style.display = i === id ? "block" : "none";
  149. }
  150. mode = id;
  151. }
  152.  
  153. var beginTime = (performance || Date).now(),
  154. prevTime = beginTime,
  155. frames = 0;
  156. var fpsPanel = addPanel(new Stats.Panel("FPS", "#0ff", "#002"));
  157. var msPanel = addPanel(new Stats.Panel("MS", "#0f0", "#020"));
  158. var memPanel = addPanel(new Stats.Panel("MB", "#f08", "#201"));
  159.  
  160. showPanel(mode);
  161.  
  162. // 获取内存信息
  163. if (window.performance && window.performance.memory) {
  164. setInterval(function () {
  165. var mem = performance.memory;
  166. memPanel.update(Math.round(mem.usedJSHeapSize / 1048576), Math.round(mem.jsHeapSizeLimit / 1048576));
  167. }, 1000);
  168. }
  169.  
  170. return {
  171. REVISION: 16,
  172. dom: wrapper,
  173. addPanel: addPanel,
  174. showPanel: showPanel,
  175. begin: function () {
  176. beginTime = (performance || Date).now();
  177. },
  178. end: function () {
  179. frames++;
  180. var time = (performance || Date).now();
  181. msPanel.update(time - beginTime, 200);
  182. if (time >= prevTime + 1000) {
  183. fpsPanel.update((frames * 1000) / (time - prevTime), 100);
  184. prevTime = time;
  185. frames = 0;
  186. }
  187. return time;
  188. },
  189. update: function () {
  190. beginTime = this.end();
  191. },
  192. };
  193. };
  194.  
  195. Stats.Panel = function (name, fg, bg) {
  196. var min = Infinity,
  197. max = 0,
  198. round = Math.round;
  199. var PR = round(window.devicePixelRatio || 1);
  200. var WIDTH = 80 * PR,
  201. HEIGHT = 48 * PR,
  202. TEXT_X = 3 * PR,
  203. TEXT_Y = 2 * PR,
  204. GRAPH_X = 3 * PR,
  205. GRAPH_Y = 15 * PR,
  206. GRAPH_WIDTH = 74 * PR,
  207. GRAPH_HEIGHT = 30 * PR;
  208.  
  209. var canvas = document.createElement("canvas");
  210. canvas.width = WIDTH;
  211. canvas.height = HEIGHT;
  212. canvas.style.cssText = "width:80px;height:48px";
  213.  
  214. var context = canvas.getContext("2d");
  215. context.font = "bold " + 9 * PR + "px Helvetica,Arial,sans-serif";
  216. context.textBaseline = "top";
  217.  
  218. context.fillStyle = bg;
  219. context.fillRect(0, 0, WIDTH, HEIGHT);
  220.  
  221. context.fillStyle = fg;
  222. context.fillText(name, TEXT_X, TEXT_Y);
  223. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  224.  
  225. context.fillStyle = bg;
  226. context.globalAlpha = 0.9;
  227. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  228.  
  229. return {
  230. dom: canvas,
  231. update: function (value, maxValue) {
  232. min = Math.min(min, value);
  233. max = Math.max(max, value);
  234. context.fillStyle = bg;
  235. context.globalAlpha = 1;
  236. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  237. context.fillStyle = fg;
  238. context.fillText(round(value) + " " + name + " (" + round(min) + "-" + round(max) + ")", TEXT_X, TEXT_Y);
  239. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  240. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  241. context.fillStyle = bg;
  242. context.globalAlpha = 0.9;
  243. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  244. },
  245. };
  246. };
  247.  
  248. // 注入Stats
  249. function injectStats() {
  250. try {
  251. const stats = new Stats();
  252. document.body.appendChild(stats.dom);
  253.  
  254. function update() {
  255. stats.update();
  256. requestAnimationFrame(update);
  257. }
  258. update();
  259.  
  260. return stats;
  261. } catch (error) {
  262. console.error("Failed to inject Stats:", error);
  263. }
  264. }
  265.  
  266. injectStats();
  267. })();