Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

perf(engine-render): cache complex SVG image rasters (#7475)

Univera49557e088dd
diff --git a/packages/engine-render/src/shape/__tests__/image.spec.ts b/packages/engine-render/src/shape/__tests__/image.spec.ts
index b130ce8479..3e9a408e27 100644
--- a/packages/engine-render/src/shape/__tests__/image.spec.ts
+++ b/packages/engine-render/src/shape/__tests__/image.spec.ts
@@ -16,16 +16,25 @@
import { describe, expect, it, vi } from 'vitest';
import { Vector2 } from '../../basics/vector2';
+import { Canvas } from '../../canvas';
+import { UniverRenderingContext } from '../../context';
import { Image } from '../image';
-function createNativeImage(width = 120, height = 80) {
+function createNativeImage(width = 120, height = 80, source?: string) {
const img = document.createElement('img');
Object.defineProperty(img, 'width', { value: width, configurable: true });
Object.defineProperty(img, 'height', { value: height, configurable: true });
Object.defineProperty(img, 'complete', { value: true, configurable: true });
+ if (source) {
+ img.src = source;
+ }
return img;
}
+function createSvgDataUrl(svg: string): string {
+ return `data:image/svg+xml,${encodeURIComponent(svg)}`;
+}
+
function createCtxMock() {
return {
save: vi.fn(),
@@ -229,4 +238,130 @@ describe('image extra', () => {
expect(ctx.clip).toHaveBeenCalledBefore(ctx.transform);
expect(ctx.drawImage).toHaveBeenCalled();
});
+
+ it('automatically raster caches only expensive static inline SVG images', () => {
+ const filteredSvg = createSvgDataUrl(`
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <defs><filter id="noise"><feTurbulence /></filter></defs>
+ <rect width="10" height="10" filter="url(#noise)" />
+ </svg>
+ `);
+ const ordinarySvg = createSvgDataUrl('<svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10" /></svg>');
+ const animatedSvg = createSvgDataUrl(`
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <defs><filter id="noise"><feTurbulence /></filter></defs>
+ <rect width="10" height="10" filter="url(#noise)"><animate attributeName="x" values="0;10" /></rect>
+ </svg>
+ `);
+ const filteredNative = createNativeImage(10, 10, filteredSvg);
+ const ordinaryNative = createNativeImage(10, 10, ordinarySvg);
+ const animatedNative = createNativeImage(10, 10, animatedSvg);
+ const filteredImage = new Image('filtered-svg', {
+ image: filteredNative,
+ left: 0,
+ top: 0,
+ width: 10,
+ height: 10,
+ });
+ const ordinaryImage = new Image('ordinary-svg', {
+ image: ordinaryNative,
+ left: 0,
+ top: 0,
+ width: 10,
+ height: 10,
+ });
+ const animatedImage = new Image('animated-svg', {
+ image: animatedNative,
+ left: 0,
+ top: 0,
+ width: 10,
+ height: 10,
+ });
+ const canvas = new Canvas({ width: 20, height: 20, pixelRatio: 1 });
+ const context = canvas.getContext();
+ const drawImage = vi.spyOn(UniverRenderingContext.prototype, 'drawImage');
+
+ for (const image of [filteredImage, ordinaryImage, animatedImage]) {
+ image.render(context);
+ image.render(context);
+ }
+
+ expect(drawImage.mock.calls.filter(([source]) => source === filteredNative)).toHaveLength(1);
+ expect(drawImage.mock.calls.filter(([source]) => source === ordinaryNative)).toHaveLength(2);
+ expect(drawImage.mock.calls.filter(([source]) => source === animatedNative)).toHaveLength(2);
+
+ drawImage.mockRestore();
+ filteredImage.dispose();
+ ordinaryImage.dispose();
+ animatedImage.dispose();
+ canvas.dispose();
+ });
+
+ it('reuses an automatic SVG raster cache within a scale bucket', () => {
+ const native = createNativeImage(100, 100, createSvgDataUrl(`
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <defs><filter id="blur"><feGaussianBlur stdDeviation="10" /></filter></defs>
+ <rect width="100" height="100" filter="url(#blur)" />
+ </svg>
+ `));
+ const image = new Image('cached-image', {
+ image: native,
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 100,
+ });
+ const canvas = new Canvas({ width: 200, height: 100, pixelRatio: 1 });
+ const context = canvas.getContext();
+ const drawImage = vi.spyOn(UniverRenderingContext.prototype, 'drawImage');
+
+ context.setTransform(1.1, 0, 0, 1.1, 0, 0);
+ image.render(context);
+ context.setTransform(1.4, 0, 0, 1.4, 0, 0);
+ image.render(context);
+ context.setTransform(1.6, 0, 0, 1.6, 0, 0);
+ image.render(context);
+
+ expect(drawImage.mock.calls.filter(([source]) => source === native)).toHaveLength(2);
+
+ drawImage.mockRestore();
+ image.dispose();
+ canvas.dispose();
+ });
+
+ it('keeps using the capped cache at high zoom', () => {
+ const native = createNativeImage(4_000, 2_000, createSvgDataUrl(`
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <defs><filter id="blur"><feGaussianBlur stdDeviation="10" /></filter></defs>
+ <rect width="4000" height="2000" filter="url(#blur)" />
+ </svg>
+ `));
+ const image = new Image('cached-image', {
+ image: native,
+ left: 0,
+ top: 0,
+ width: 4_000,
+ height: 2_000,
+ });
+ const canvas = new Canvas({ width: 200, height: 100, pixelRatio: 1 });
+ const context = canvas.getContext();
+ const drawImage = vi.spyOn(UniverRenderingContext.prototype, 'drawImage');
+
+ context.setTransform(0.5, 0, 0, 0.5, 0, 0);
+ image.render(context);
+ context.setTransform(2, 0, 0, 2, 0, 0);
+ image.render(context);
+
+ expect(drawImage.mock.calls.filter(([source]) => source === native)).toHaveLength(1);
+ const cacheCanvas = drawImage.mock.calls.find(([source]) => source instanceof HTMLCanvasElement)?.[0];
+ if (!(cacheCanvas instanceof HTMLCanvasElement)) {
+ throw new TypeError('Expected the SVG raster cache canvas to be rendered');
+ }
+ expect(cacheCanvas.width * cacheCanvas.height).toBeLessThanOrEqual(4_000_000);
+ expect(drawImage.mock.calls.filter(([source]) => source === cacheCanvas)).toHaveLength(2);
+
+ drawImage.mockRestore();
+ image.dispose();
+ canvas.dispose();
+ });
});
diff --git a/packages/engine-render/src/shape/image.ts b/packages/engine-render/src/shape/image.ts
index 7e20dd0148..8f3781374a 100644
--- a/packages/engine-render/src/shape/image.ts
+++ b/packages/engine-render/src/shape/image.ts
@@ -24,6 +24,54 @@ import { RENDER_CLASS_TYPE, Transform, Vector2 } from '../basics';
import { offsetRotationAxis } from '../basics/offset-rotation-axis';
import { Shape } from './shape';
+const INLINE_SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml(?:;[^,]*)?,/i;
+const SVG_FILTER_REFERENCE_PATTERN = /\bfilter\s*=/i;
+const SVG_EXPENSIVE_FILTER_PATTERN = /<fe(?:Turbulence|DisplacementMap|GaussianBlur)\b/i;
+const SVG_ANIMATION_PATTERN = /<(?:animate(?:Color|Motion|Transform)?|set)\b|@keyframes\b/i;
+const RASTER_CACHE_MAX_PIXEL_COUNT = 4_000_000;
+const RASTER_CACHE_MAX_DIMENSION = 4_096;
+const RASTER_CACHE_PIXEL_RATIO_STEP = 0.5;
+
+function shouldRasterCacheSvg(source?: string): boolean {
+ const prefix = source && INLINE_SVG_DATA_URL_PATTERN.exec(source)?.[0];
+ if (!prefix) {
+ return false;
+ }
+
+ try {
+ const payload = source.slice(prefix.length);
+ const svg = prefix.toLowerCase().includes(';base64,') ? atob(payload) : decodeURIComponent(payload);
+ return !SVG_ANIMATION_PATTERN.test(svg) &&
+ SVG_FILTER_REFERENCE_PATTERN.test(svg) &&
+ SVG_EXPENSIVE_FILTER_PATTERN.test(svg);
+ } catch {
+ return false;
+ }
+}
+
+function resolveRasterCachePixelRatio(width: number, height: number, requestedPixelRatio: number): number {
+ if (width <= 0 || height <= 0) {
+ return requestedPixelRatio;
+ }
+
+ const dimensionPixelRatioLimit = Math.min(
+ RASTER_CACHE_MAX_DIMENSION / width,
+ RASTER_CACHE_MAX_DIMENSION / height
+ );
+ const pixelLimitedPixelRatio = Math.sqrt(RASTER_CACHE_MAX_PIXEL_COUNT / (width * height));
+ const pixelRatioLimit = Math.min(dimensionPixelRatioLimit, pixelLimitedPixelRatio);
+ const pixelRatio = requestedPixelRatio + RASTER_CACHE_PIXEL_RATIO_STEP > pixelRatioLimit
+ ? pixelRatioLimit
+ : requestedPixelRatio;
+ if (pixelRatio < pixelLimitedPixelRatio) {
+ return pixelRatio;
+ }
+
+ const physicalWidth = Math.floor(width * pixelLimitedPixelRatio);
+ const physicalHeight = Math.floor(RASTER_CACHE_MAX_PIXEL_COUNT / physicalWidth);
+ return Math.min(pixelRatio, (physicalWidth - 1) / width, (physicalHeight - 1) / height);
+}
+
export interface IShapeClipBounds {
left: number;
top: number;
@@ -79,6 +127,10 @@ export class Image extends Shape<IImageProps> {
private _clipService: Nullable<IImageShapeClipService> = null;
+ private _rasterCacheSource = '';
+
+ private _autoRasterCache = false;
+
override objectType = ObjectType.IMAGE;
override isDrawingObject: boolean = true;
@@ -131,6 +183,20 @@ export class Image extends Shape<IImageProps> {
return this._props.clipBounds;
}
+ private _shouldRasterCache(): boolean {
+ const source = this._native?.src || this._props.url || '';
+ if (source !== this._rasterCacheSource) {
+ const previous = this._autoRasterCache;
+ this._rasterCacheSource = source;
+ this._autoRasterCache = shouldRasterCacheSvg(source);
+ if (previous && !this._autoRasterCache) {
+ this._releaseRenderCache();
+ }
+ }
+
+ return this._autoRasterCache;
+ }
+
setOpacity(opacity: number) {
this._props.opacity = opacity;
this.makeDirty(true);
@@ -377,12 +443,37 @@ export class Image extends Shape<IImageProps> {
}
protected override _draw(ctx: UniverRenderingContext, _bounds?: IViewportInfo, renderWidth?: number, renderHeight?: number) {
- if (this._native == null) {
+ const native = this._native;
+ if (native == null) {
return;
}
const w = renderWidth ?? this.width;
const h = renderHeight ?? this.height;
+ if (this._shouldRasterCache()) {
+ const transform = ctx.getTransform();
+ const requestedPixelRatio = Math.max(
+ Math.hypot(transform.a, transform.b),
+ Math.hypot(transform.c, transform.d)
+ );
+ const pixelRatio = resolveRasterCachePixelRatio(
+ w,
+ h,
+ Math.ceil(requestedPixelRatio / RASTER_CACHE_PIXEL_RATIO_STEP) * RASTER_CACHE_PIXEL_RATIO_STEP
+ );
+ this._renderWithCache(
+ ctx,
+ { left: -w / 2, top: -h / 2, right: w / 2, bottom: h / 2 },
+ (cacheContext) => this._drawNative(cacheContext, native, w, h),
+ pixelRatio
+ );
+ return;
+ }
+
+ this._drawNative(ctx, native, w, h);
+ }
+
+ private _drawNative(ctx: UniverRenderingContext, native: HTMLImageElement, w: number, h: number): void {
// Shape clip: when prstGeom is set and a clip service is available,
// clip the image to the shape outline (e.g. ellipse, roundRect, etc.)
if (this.prstGeom && this._clipService) {
@@ -409,14 +500,14 @@ export class Image extends Shape<IImageProps> {
const scaleW = this.width > 0 ? drawWidth / this.width : 1;
const scaleH = this.height > 0 ? drawHeight / this.height : 1;
ctx.drawImage(
- this._native,
+ native,
drawLeft - left * scaleW,
drawTop - top * scaleH,
drawWidth + (right + left) * scaleW,
drawHeight + (bottom + top) * scaleH
);
} else {
- ctx.drawImage(this._native, drawLeft, drawTop, drawWidth, drawHeight);
+ ctx.drawImage(native, drawLeft, drawTop, drawWidth, drawHeight);
}
ctx.restore();
return;
@@ -432,14 +523,14 @@ export class Image extends Shape<IImageProps> {
ctx.rect(-w / 2, -h / 2, w, h);
ctx.clip();
ctx.drawImage(
- this._native,
+ native,
-left * scaleW - w / 2,
-top * scaleH - h / 2,
w + (right + left) * scaleW,
h + (bottom + top) * scaleH
);
} else {
- ctx.drawImage(this._native, -w / 2, -h / 2, w, h);
+ ctx.drawImage(native, -w / 2, -h / 2, w, h);
}
}
diff --git a/packages/engine-render/src/shape/shape.ts b/packages/engine-render/src/shape/shape.ts
index 751ebdeb79..9cf692a785 100644
--- a/packages/engine-render/src/shape/shape.ts
+++ b/packages/engine-render/src/shape/shape.ts
@@ -27,6 +27,16 @@ export type LineCap = 'butt' | 'round' | 'square';
export type PaintFirst = 'fill' | 'stroke';
const BASE_OBJECT_ARRAY_Set = new Set(BASE_OBJECT_ARRAY);
+
+function resolveRenderCachePixelRatio(ctx: UniverRenderingContext, fixedPixelRatio?: number): number {
+ if (fixedPixelRatio !== undefined) {
+ return fixedPixelRatio;
+ }
+
+ const transform = ctx.getTransform();
+ return Math.max(Math.hypot(transform.a, transform.b), Math.hypot(transform.c, transform.d));
+}
+
export interface IShapeProps extends IObjectFullState, ISize, IOffset, IScale {
rotateEnabled?: boolean;
resizeEnabled?: boolean;
@@ -395,12 +405,10 @@ export abstract class Shape<T extends IShapeProps> extends BaseObject {
protected _renderWithCache(
ctx: UniverRenderingContext,
bounds: IBoundRectNoAngle,
- draw: (cacheContext: UniverRenderingContext) => void
+ draw: (cacheContext: UniverRenderingContext) => void,
+ fixedPixelRatio?: number
): void {
- const transform = ctx.getTransform();
- const scaleX = Math.hypot(transform.a, transform.b);
- const scaleY = Math.hypot(transform.c, transform.d);
- const pixelRatio = Math.max(scaleX, scaleY);
+ const pixelRatio = resolveRenderCachePixelRatio(ctx, fixedPixelRatio);
if (pixelRatio <= Number.EPSILON) {
return;
}