Appearance
工具方法
RayChart 导出一组实用的工具 API:性能监控、数据验证、WebGL 能力检测、对象池与数据缓存。
性能监控
globalMonitor
全局性能监控器(PerformanceMonitor 实例),提供方法级计时与统计分析。
仅开发环境启用
globalMonitor 仅在开发环境(import.meta.env.DEV)采集数据;生产构建中 start/end 直接返回 0,不产生任何开销。生产环境需要采样时请自行 new PerformanceMonitor(true)。
javascript
import { globalMonitor } from 'raychart'
// 手动计时
const start = globalMonitor.start('render')
// ... 执行代码
globalMonitor.end('render', start)
// 自动计时(包裹函数,自动 start/end)
globalMonitor.measure('render', () => {
// ... 执行代码
})
// 异步函数同样支持
await globalMonitor.measureAsync('fetchData', async () => {
// ...
})获取统计
javascript
// 获取指定标签的统计(label 必填,无数据时返回 null)
const stats = globalMonitor.getStats('render')
if (stats) {
console.log(`平均: ${stats.avg}ms, 最大: ${stats.max}ms, 次数: ${stats.count}`)
}
// 获取全部标签的报告 { label: PerformanceMetric }
const report = globalMonitor.getReport()
// 打印报告到控制台
globalMonitor.printReport()
// 清除数据(不传 label 则全部清除)
globalMonitor.clear('render')PerformanceMetric 字段:
| 字段 | 说明 |
|---|---|
count | 采样次数 |
total | 总耗时(ms) |
avg | 平均耗时(ms) |
min / max | 最小 / 最大耗时(ms) |
last | 最近一次耗时(ms) |
DEV_MONITOR
开发环境专用别名:开发环境等价于 globalMonitor,生产环境为全空操作对象(方法可安全调用但不采集):
javascript
import { DEV_MONITOR } from 'raychart'
DEV_MONITOR.measure('update', () => {
// 生产环境直接执行函数,不采集
})FPS 与内存监控
javascript
import { globalFPSMonitor, globalMemoryMonitor } from 'raychart'
// FPS:每帧调用 tick() 采样,保留最近 60 帧
function renderLoop() {
globalFPSMonitor.tick()
const fps = globalFPSMonitor.getAverageFPS()
requestAnimationFrame(renderLoop)
}
// 内存(仅 Chrome / Edge 等支持 performance.memory 的环境可用)
const usage = globalMemoryMonitor.getMemoryUsage()
if (usage) {
console.log(globalMemoryMonitor.formatBytes(usage.usedJSHeapSize))
}数据验证
DataValidator
基于路径规则的轻量数据验证器,支持嵌套对象与数组元素验证。
javascript
import { DataValidator, CommonRules } from 'raychart'
const schema = {
series: CommonRules.required('series 不能为空'),
'series.0.data': CommonRules.array(1, undefined, '至少一个数据点'),
'series.0.itemStyle.metalness': CommonRules.percentage('metalness 需在 0-100 之间'),
}
// 方式一:返回结果对象(不抛错)
const result = DataValidator.validate(option, schema)
if (!result.valid) {
result.errors.forEach((e) => console.log(`${e.path}: ${e.message}`))
}
// 方式二:验证失败直接抛异常
try {
DataValidator.validateOrThrow(option, schema)
} catch (error) {
console.error('校验失败:', error.message)
}validate 返回 { valid: boolean, errors: { path, message, value? }[] }。
CommonRules 预设规则
| 规则 | 签名 | 说明 |
|---|---|---|
required(message?) | () => rule | 必填 |
string(message?) | () => rule | 字符串类型 |
number(min?, max?, message?) | () => rule | 数值范围 |
array(minLength?, maxLength?, message?) | () => rule | 数组长度 |
enum(values, message?) | () => rule | 枚举取值 |
positive(message?) | () => rule | ≥ 0 |
percentage(message?) | () => rule | 0-100 |
color(message?) | () => rule | 颜色格式(#hex 或 rgb()) |
WebGL 能力检测
javascript
import {
checkWebGLSupport,
getWebGLCapabilities,
checkRequiredExtensions,
getRecommendedRendererConfig,
} from 'raychart'
const support = checkWebGLSupport()
// { supported: true, version: 2 }
const caps = getWebGLCapabilities()
// { maxTextureSize, maxCubeMapTextureSize, maxVertexAttributes, ... , extensions: { floatTextures, depthTexture, ... } }
// extensions 为对象(非数组),字段含义见下方 WebGL 能力说明
const result = checkRequiredExtensions(['EXT_color_space_linear', 'OES_texture_float_linear'])
// { supported: true, missing: [] }
const config = getRecommendedRendererConfig()
// { antialias: true, powerPreference: 'high-performance', precision: 'highp' }对象池
高频创建/销毁的对象(向量、矩阵、粒子等)建议复用对象池,避免 GC 抖动:
javascript
import { ObjectPool, vector3Pool, withPooledVector3 } from 'raychart'
// 自定义对象池:new ObjectPool(factory, maxSize?, reset?)
const pool = new ObjectPool(
() => ({ x: 0, y: 0, z: 0 }),
100, // 池容量
(obj) => { obj.x = 0; obj.y = 0; obj.z = 0 } // 归还时重置
)
const obj = pool.acquire()
// ... 使用
pool.release(obj)内置池与辅助函数:
| 名称 | 说明 |
|---|---|
vector3Pool / vector2Pool | 向量池 |
colorPool / quaternionPool / matrix4Pool / eulerPool | 颜色 / 四元数 / 矩阵 / 欧拉角池 |
box3Pool / spherePool | 包围盒 / 球池 |
withPooledVector3(fn) | 从池中取向量、调用 fn(vec) 后自动归还 |
withPooledVectors(count, fn) | 批量取用、自动归还 |
javascript
// 内置向量池 + 自动归还
const result = withPooledVector3((v) => {
v.set(1, 2, 3)
return v.length()
})数据缓存
javascript
import { DataCache, globalDataCache } from 'raychart'
const cache = new DataCache(200) // 容量 200 条,超过自动淘汰最旧数据
cache.set('option', { series: [] })
const value = cache.get('option')
// 数据是否变化(内部对数据做哈希比对)
const changed = cache.hasChanged('option', newValue)
cache.clear() // 清空全部缓存(注意是 clear())TypeScript 支持
所有工具方法均带完整类型定义:
typescript
import type { PerformanceMetric, ValidationSchema, WebGLCapabilities } from 'raychart'