Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix(video-export): show globe stars in preview and exported video (#3636)
Igor Dykhta24d554d01e92
diff --git a/src/components/src/modals/globe-export-video-container.tsx b/src/components/src/modals/globe-export-video-container.tsxindex 508bd41e4..5158d9419 100644--- a/src/components/src/modals/globe-export-video-container.tsx+++ b/src/components/src/modals/globe-export-video-container.tsx@@ -22,7 +22,7 @@ import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';import {parseSetCameraType, scaleToVideoExport, getResolutionSetting} from './hubble-utils';import {GlobeExportVideoPreview} from './globe-export-video-preview';import SwipeExportSettings from './swipe-export-settings';-import {getGlobeClearColor} from '@kepler.gl/deckgl-layers';+import {drawStarsBackground, getGlobeClearColor, getStarsBackgroundImage} from '@kepler.gl/deckgl-layers';// No-op for the swipe-specific settings callbacks that this single-map globe// exporter doesn't use (the swipe controls are hidden via `hideSwipe`).@@ -311,6 +311,12 @@ export class GlobeExportVideoPanelContainer extends Component<return `rgb(${r}, ${g}, ${b})`;}+ /** Starfield behind the globe, matching the live map's CSS background. */+ areStarsEnabled(): boolean {+ const globe = this.props.mapData?.mapState?.globe;+ return Boolean(globe?.enabled && globe?.config?.stars);+ }+setStateAndNotify(update: GlobeExportVideoSettings) {const {onSettingsChange} = this.props;const {mediaType, cameraPreset, fileName, resolution, durationMs} = this.state;@@ -441,9 +447,14 @@ export class GlobeExportVideoPanelContainer extends Component<if (offCtx) {// deck's canvas is transparent where the globe isn't drawn// (clearColor is disabled to keep picking intact), so fill the- // configured background first, then composite the deck frame.+ // configured background first, tile the starfield (the live map+ // paints stars as a CSS background, which canvas capture misses),+ // then composite the deck frame.offCtx.fillStyle = this.getBackgroundColor();offCtx.fillRect(0, 0, width, height);+ if (this.areStarsEnabled()) {+ drawStarsBackground(offCtx, width, height);+ }offCtx.drawImage(deckCanvas, 0, 0, width, height);}@@ -536,6 +547,7 @@ export class GlobeExportVideoPanelContainer extends Component<durationMs={durationMs}deckProps={deckProps}backgroundColor={this.getBackgroundColor()}+ starsImage={this.areStarsEnabled() ? getStarsBackgroundImage() : null}/><SwipeExportSettingsdurationMs={durationMs}diff --git a/src/components/src/modals/globe-export-video-preview.tsx b/src/components/src/modals/globe-export-video-preview.tsxindex 11bef199a..fddbb189a 100644--- a/src/components/src/modals/globe-export-video-preview.tsx+++ b/src/components/src/modals/globe-export-video-preview.tsx@@ -9,11 +9,20 @@ import styled from 'styled-components';import {DeckAdapter} from '@hubble.gl/core';import {EXPORT_DECK_DEVICE_PROPS} from './hubble-utils';-const PreviewContainer = styled.div<{$width: number; $height: number; $background: string}>`+const PreviewContainer = styled.div<{+ $width: number;+ $height: number;+ $background: string;+ $starsImage?: string | null;+}>`width: ${props => props.$width}px;height: ${props => props.$height}px;position: relative;- background: ${props => props.$background};+ background-color: ${props => props.$background};+ ${props =>+ props.$starsImage+ ? `background-image: url('${props.$starsImage}'); background-repeat: repeat;`+ : ''}`;export type GlobeExportVideoPreviewProps = {@@ -29,6 +38,8 @@ export type GlobeExportVideoPreviewProps = {durationMs: number;/** CSS color string for the area the globe does not cover. */backgroundColor: string;+ /** Tileable star-field data URL, matching the live globe map CSS background. */+ starsImage?: string | null;};/**@@ -67,8 +78,16 @@ export class GlobeExportVideoPreview extends Component<GlobeExportVideoPreviewPr}render() {- const {adapter, deckProps, viewState, setViewState, resolution, exportVideoWidth, backgroundColor} =- this.props;+ const {+ adapter,+ deckProps,+ viewState,+ setViewState,+ resolution,+ exportVideoWidth,+ backgroundColor,+ starsImage+ } = this.props;const {width, height} = this._getContainer();const deck = this.deckRef.current;@@ -93,7 +112,12 @@ export class GlobeExportVideoPreview extends Component<GlobeExportVideoPreviewPrconst pixelRatio = Math.max(1, resolution[0] / exportVideoWidth);return (- <PreviewContainer $width={width} $height={height} $background={backgroundColor}>+ <PreviewContainer+ $width={width}+ $height={height}+ $background={backgroundColor}+ $starsImage={starsImage}+ ><DeckGLref={ref => {this.deckRef.current = (ref?.deck as any) || null;diff --git a/src/components/src/modals/swipe-composite-utils.spec.ts b/src/components/src/modals/swipe-composite-utils.spec.tsnew file mode 100644index 000000000..cae724bcb--- /dev/null+++ b/src/components/src/modals/swipe-composite-utils.spec.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++jest.mock('@kepler.gl/deckgl-layers', () => ({+ drawStarsBackground: jest.fn()+}));++import {drawStarsBackground} from '@kepler.gl/deckgl-layers';+import {compositeSwipeFrame} from './swipe-composite-utils';++function mockCanvas(width: number, height: number, ctx: CanvasRenderingContext2D | null) {+ return {+ width,+ height,+ getContext: () => ctx+ } as unknown as HTMLCanvasElement;+}++function mockCompositeCtx() {+ return {+ clearRect: jest.fn(),+ fillRect: jest.fn(),+ drawImage: jest.fn(),+ save: jest.fn(),+ restore: jest.fn(),+ beginPath: jest.fn(),+ rect: jest.fn(),+ clip: jest.fn(),+ fillStyle: '',+ strokeStyle: '',+ lineWidth: 0,+ shadowColor: '',+ shadowBlur: 0,+ moveTo: jest.fn(),+ lineTo: jest.fn(),+ stroke: jest.fn(),+ arc: jest.fn(),+ fill: jest.fn(),+ closePath: jest.fn()+ };+}++describe('compositeSwipeFrame', () => {+ afterEach(() => {+ jest.clearAllMocks();+ });++ test('tiles stars after the globe background color when showStars is true', () => {+ const ctx = mockCompositeCtx();+ const left = mockCanvas(10, 10, ctx as unknown as CanvasRenderingContext2D);+ const right = mockCanvas(10, 10, ctx as unknown as CanvasRenderingContext2D);+ const output = mockCanvas(100, 50, ctx as unknown as CanvasRenderingContext2D);++ compositeSwipeFrame(left, right, output, 50, false, 'rgb(1, 2, 3)', true);++ expect(ctx.fillStyle).toBe('rgb(1, 2, 3)');+ expect(ctx.fillRect).toHaveBeenCalledWith(0, 0, 100, 50);+ expect(drawStarsBackground).toHaveBeenCalledWith(ctx, 100, 50);+ expect(ctx.fillRect.mock.invocationCallOrder[0]).toBeLessThan(+ (drawStarsBackground as jest.Mock).mock.invocationCallOrder[0]+ );+ });++ test('does not draw stars when showStars is omitted', () => {+ const ctx = mockCompositeCtx();+ const left = mockCanvas(10, 10, ctx as unknown as CanvasRenderingContext2D);+ const right = mockCanvas(10, 10, ctx as unknown as CanvasRenderingContext2D);+ const output = mockCanvas(100, 50, ctx as unknown as CanvasRenderingContext2D);++ compositeSwipeFrame(left, right, output, 50, false, 'rgb(1, 2, 3)');++ expect(drawStarsBackground).not.toHaveBeenCalled();+ });+});diff --git a/src/components/src/modals/swipe-composite-utils.ts b/src/components/src/modals/swipe-composite-utils.tsindex 7583996e0..c7d039878 100644--- a/src/components/src/modals/swipe-composite-utils.ts+++ b/src/components/src/modals/swipe-composite-utils.ts@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl projectimport {easeInOut} from 'popmotion';+import {drawStarsBackground} from '@kepler.gl/deckgl-layers';export type SwipeEasing = 'linear' | 'ease-in-out';@@ -91,7 +92,8 @@ export function compositeSwipeFrame(outputCanvas: HTMLCanvasElement,percentage: number,showDivider: boolean = true,- backgroundColor?: string+ backgroundColor?: string,+ showStars?: boolean): void {const ctx = outputCanvas.getContext('2d');if (!ctx) return;@@ -111,6 +113,12 @@ export function compositeSwipeFrame(ctx.fillRect(0, 0, w, h);}+ // Stars are a CSS background on the live globe map, so they must be tiled+ // onto the composite canvas or they won't appear in preview or export.+ if (showStars) {+ drawStarsBackground(ctx, w, h);+ }+// Draw right (background) canvas fullyctx.drawImage(rightCanvas, 0, 0, w, h);diff --git a/src/components/src/modals/swipe-export-video-preview.tsx b/src/components/src/modals/swipe-export-video-preview.tsxindex fa79fa806..3657f6595 100644--- a/src/components/src/modals/swipe-export-video-preview.tsx+++ b/src/components/src/modals/swipe-export-video-preview.tsx@@ -178,13 +178,17 @@ export class SwipeExportVideoPreview extends Component<if (!leftCanvas || !rightCanvas || !outputCanvas) return;const percentage = this._getCurrentSwipePercentage();+ const globe = this.props.mapData?.mapState?.globe;+ const showStars = Boolean(globe?.enabled && globe?.config?.stars);+compositeSwipeFrame(leftCanvas,rightCanvas,outputCanvas,percentage,true,- this.props.backgroundColor+ this.props.backgroundColor,+ showStars);}diff --git a/src/deckgl-layers/src/globe/globe-stars-layer.spec.ts b/src/deckgl-layers/src/globe/globe-stars-layer.spec.tsnew file mode 100644index 000000000..bab607c85--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-stars-layer.spec.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {drawStarsBackground} from './globe-stars-layer';++describe('globe-stars-layer', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ test('drawStarsBackground tiles the star canvas with a repeating pattern', () => {+ const tileCtx = {+ clearRect: jest.fn(),+ beginPath: jest.fn(),+ arc: jest.fn(),+ fill: jest.fn(),+ fillStyle: ''+ };+ const originalGetContext = HTMLCanvasElement.prototype.getContext;+ jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function getContext(+ this: HTMLCanvasElement,+ type: string+ ) {+ if (type === '2d') {+ return tileCtx as unknown as CanvasRenderingContext2D;+ }+ return originalGetContext.call(this, type);+ });++ const pattern = {id: 'stars-pattern'};+ const destCtx = {+ createPattern: jest.fn(() => pattern),+ fillRect: jest.fn(),+ fillStyle: '' as string | CanvasPattern+ };++ drawStarsBackground(destCtx as unknown as CanvasRenderingContext2D, 1280, 720);++ expect(destCtx.createPattern).toHaveBeenCalledWith(expect.any(HTMLCanvasElement), 'repeat');+ expect(destCtx.fillStyle).toBe(pattern);+ expect(destCtx.fillRect).toHaveBeenCalledWith(0, 0, 1280, 720);+ });+});diff --git a/src/deckgl-layers/src/globe/globe-stars-layer.ts b/src/deckgl-layers/src/globe/globe-stars-layer.tsindex 29087654d..1890e7359 100644--- a/src/deckgl-layers/src/globe/globe-stars-layer.ts+++ b/src/deckgl-layers/src/globe/globe-stars-layer.ts@@ -2,9 +2,11 @@// Copyright contributors to the kepler.gl project/**- * Generates a CSS-compatible star-field background image as a data URL.- * The stars are rendered onto an offscreen canvas, tiled seamlessly via CSS- * `background-repeat`. The result is deterministic (seeded PRNG) and cached+ * Generates a tileable star-field used behind the globe.+ * The live map and video-export preview paint it as a CSS `background-image`+ * with `background-repeat: repeat`. Video-export capture (which only reads+ * canvas pixels) tiles the same image onto a 2D context via+ * `drawStarsBackground`. The result is deterministic (seeded PRNG) and cached* so it's only generated once.*/@@ -26,27 +28,21 @@ function seededRandom(seed: number): () => number {const TRANSPARENT_PIXEL ='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';+let cachedCanvas: HTMLCanvasElement | null = null;let cachedDataUrl: string | null = null;-/**- * Returns a data URL of a tileable star-field image (512×512 PNG).- * Generates the image once and caches it for subsequent calls.- */-export function getStarsBackgroundImage(): string {- if (cachedDataUrl) return cachedDataUrl;-+function generateStarsTile(): HTMLCanvasElement | null {if (typeof document === 'undefined') {- // SSR fallback: return a transparent 1x1 pixel to avoid url() triggering a page request- return TRANSPARENT_PIXEL;+ return null;}const canvas = document.createElement('canvas');canvas.width = STAR_CANVAS_SIZE;canvas.height = STAR_CANVAS_SIZE;const ctx = canvas.getContext('2d');- if (!ctx) return (cachedDataUrl = TRANSPARENT_PIXEL);+ if (!ctx) return null;- // Transparent background so CSS backgroundColor shows through+ // Transparent background so CSS backgroundColor / canvas fill shows throughctx.clearRect(0, 0, STAR_CANVAS_SIZE, STAR_CANVAS_SIZE);const random = seededRandom(42);@@ -64,7 +60,47 @@ export function getStarsBackgroundImage(): string {ctx.fill();}+ return canvas;+}++function getStarsTileCanvas(): HTMLCanvasElement | null {+ if (cachedCanvas) return cachedCanvas;+ cachedCanvas = generateStarsTile();+ return cachedCanvas;+}++/**+ * Returns a data URL of a tileable star-field image (512×512 PNG).+ * Generates the image once and caches it for subsequent calls.+ */+export function getStarsBackgroundImage(): string {+ if (cachedDataUrl) return cachedDataUrl;++ const canvas = getStarsTileCanvas();+ if (!canvas) {+ // SSR / missing 2D context: return a transparent 1x1 pixel so url() never+ // resolves to an empty value that could trigger a request for the document.+ return (cachedDataUrl = TRANSPARENT_PIXEL);+ }+cachedDataUrl = canvas.toDataURL('image/png');return cachedDataUrl;}+/**+ * Tile the star-field onto a 2D canvas (e.g. video-export frame capture).+ * Stars are drawn with alpha so the caller should fill the background color first.+ */+export function drawStarsBackground(+ ctx: CanvasRenderingContext2D,+ width: number,+ height: number+): void {+ const tile = getStarsTileCanvas();+ if (!tile || width <= 0 || height <= 0) return;+ const pattern = ctx.createPattern(tile, 'repeat');+ if (!pattern) return;+ ctx.fillStyle = pattern;+ ctx.fillRect(0, 0, width, height);+}+diff --git a/src/deckgl-layers/src/globe/index.ts b/src/deckgl-layers/src/globe/index.tsindex 5c38e89f2..a6c01eb93 100644--- a/src/deckgl-layers/src/globe/index.ts+++ b/src/deckgl-layers/src/globe/index.ts@@ -39,4 +39,4 @@ export type {GlobeBasemapProvider, GlobeAttribution} from './globe-layers';export {MVTLabelLayer} from './mvt-label-layer';export {default as EnhancedMultiIconLayer} from './enhanced-multi-icon-layer';export {KeplerGlobeView} from './globe-view';-export {getStarsBackgroundImage} from './globe-stars-layer';+export {getStarsBackgroundImage, drawStarsBackground} from './globe-stars-layer';