|
| 1 | +// deck.gl |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | +// Copyright (c) vis.gl contributors |
| 4 | + |
| 5 | +import {Widget, WidgetProps} from '@deck.gl/core'; |
| 6 | +import type {WidgetPlacement, Deck} from '@deck.gl/core'; |
| 7 | + |
| 8 | +/** Properties for the FpsWidget. */ |
| 9 | +export type FpsWidgetProps = WidgetProps & { |
| 10 | + /** Widget positioning within the view. Default 'top-left'. */ |
| 11 | + placement?: WidgetPlacement; |
| 12 | +}; |
| 13 | + |
| 14 | +/** |
| 15 | + * Displays the average frames per second reported by the Deck instance. |
| 16 | + */ |
| 17 | +export class FpsWidget extends Widget<FpsWidgetProps> { |
| 18 | + static defaultProps: Required<FpsWidgetProps> = { |
| 19 | + ...Widget.defaultProps, |
| 20 | + id: 'fps', |
| 21 | + placement: 'top-left' |
| 22 | + }; |
| 23 | + |
| 24 | + className = 'deck-widget-fps'; |
| 25 | + placement: WidgetPlacement = 'top-left'; |
| 26 | + |
| 27 | + private _lastFps: number = -1; |
| 28 | + |
| 29 | + constructor(props: FpsWidgetProps = {}) { |
| 30 | + super(props, FpsWidget.defaultProps); |
| 31 | + this.placement = props.placement ?? this.placement; |
| 32 | + } |
| 33 | + |
| 34 | + setProps(props: Partial<FpsWidgetProps>): void { |
| 35 | + if (props.placement) { |
| 36 | + this.placement = props.placement; |
| 37 | + } |
| 38 | + super.setProps(props); |
| 39 | + } |
| 40 | + |
| 41 | + onRenderHTML(rootElement: HTMLElement): void { |
| 42 | + const fps = this._getFps(); |
| 43 | + rootElement.innerText = `FPS:\n${fps}`; |
| 44 | + rootElement.style.backgroundColor = 'white'; |
| 45 | + rootElement.style.fontFamily = 'monospace'; |
| 46 | + rootElement.style.fontSize = '8px'; |
| 47 | + rootElement.style.fontWeight = '700'; // Make font bolder on click |
| 48 | + } |
| 49 | + |
| 50 | + onRedraw({}: {viewports: any[]; layers: any[]}): void { |
| 51 | + const fps = this._getFps(); |
| 52 | + if (fps !== this._lastFps) { |
| 53 | + this._lastFps = fps; |
| 54 | + this.updateHTML(); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + onAdd({}: {deck: Deck<any>; viewId: string | null}): void { |
| 59 | + this._lastFps = this._getFps(); |
| 60 | + this.updateHTML(); |
| 61 | + } |
| 62 | + |
| 63 | + _getFps(): number { |
| 64 | + // @ts-expect-error protected |
| 65 | + return Math.round(this.deck.metrics.fps ?? 0); |
| 66 | + } |
| 67 | +} |
0 commit comments