javascript - 动态 CSS 内容性能
问题描述
我有一个 requestAnimationFrame 循环,我需要将 innerText 设置为使用 javascript 测量的 fps。我想知道是否有更有效的方法来做到这一点(因为我认为设置 innerText 会导致每帧重排/重绘)?仅对于 fps,这可能不会导致任何性能损失,但由于我想使用这种机制添加/更改更多元素,我想知道是否有更有效的方法来做到这一点?
我尝试更改 css 变量:#fps-counter:before { content: var(--css-fps-var) }
并在循环中更改 --css-fps-var ,但这没有用。现在我解决了一个我使用数据属性更新的数据属性:#fps-counter:before { content: attr(data-fps); }
我不知道这是否会更好,我认为它应该但我不确定..有没有更好的方法来做到这一点?
编辑1:
不幸的是我不能使用画布,我必须使用 DOM 元素来实现这一点..
解决方案
在 a 中将值绘制为文本<canvas>
不会触发 DOM 的任何布局/重排:
const times = [];
let fps;
const canvas = document.getElementById('fpsCounter');
const ctx = canvas.getContext('2d');
ctx.font = '16px sans-serif';
function refreshLoop() {
window.requestAnimationFrame(() => {
const now = performance.now();
while (times.length > 0 && times[0] <= now - 1000) {
times.shift();
}
times.push(now);
fps = times.length;
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#FFFFFF';
ctx.fillText(`fps: ${fps}`, 10, 16);
refreshLoop();
});
}
refreshLoop();
<canvas id="fpsCounter" width="100" height="20" style="position: absolute; top: 10px; left: 10px;"/>
推荐阅读
- git - 如何打印子模块级别/深度
- delphi - 如何使用文件“映射/共享内存”从我的 Delphi 应用程序中获取 Inno 安装程序“进度状态/日志”
- c# - 如何在 Xamarin Forms 中更改选项卡式页面指示器的颜色
- python - 当字段为 NaN 时,是否有可能在插入字符串时将字段设为空白?
- javascript - Flask + jQuery:线程完成后渲染不同的模板
- javascript - 在 js 中平移和缩放“无限”方格纸背景
- python - 根据匹配的选定列清理和重新排序两个数组的最有效方法
- node.js - Nuxt 致命错误 - 导出中未定义子路径“./package.json”
- influxdb - Influx (2.x) 列出身份验证令牌
- php - Laravel 任何带有可选 GET 参数的路由