Repository navigation
feat(h5): 支持 createOffscreenCanvas #19674
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Single-Dancer
merged 3 commits into
NervJS:main
from
Jarvis636431:codex/h5-offscreen-canvas
Nov 30, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
76 changes: 76 additions & 0 deletions
76
packages/taro-components/__tests__/offscreen-canvas.e2e.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { newE2EPage } from '@stencil/core/testing' | ||
| import { build } from 'esbuild' | ||
|
|
||
| it('draws an image and reads its pixel with the H5 HTML canvas fallback', async () => { | ||
| const { outputFiles } = await build({ | ||
| stdin: { | ||
| contents: ` | ||
| export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas' | ||
| `, | ||
| resolveDir: __dirname, | ||
| }, | ||
| bundle: true, | ||
| globalName: 'h5Canvas', | ||
| write: false, | ||
| }) | ||
| const page = await newE2EPage() | ||
| await page.addScriptTag({ content: outputFiles[0].text }) | ||
| const result = await page.evaluate(async () => { | ||
| Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: undefined }) | ||
| const { h5Canvas } = window as unknown as { | ||
| h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas') | ||
| } | ||
| const canvas = h5Canvas.createOffscreenCanvas({ type: '2d', width: 1, height: 1 }) | ||
| const context = canvas.getContext('2d') | ||
| if (!context) throw new Error('2D context is unavailable') | ||
|
|
||
| const image = canvas.createImage() | ||
| await new Promise<void>((resolve, reject) => { | ||
| image.onload = () => resolve() | ||
| image.onerror = reject | ||
| image.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="red"/></svg>' | ||
| }) | ||
| context.clearRect(0, 0, 1, 1) | ||
| context.drawImage(image, 0, 0) | ||
| return { | ||
| pixel: Array.from(context.getImageData(0, 0, 1, 1).data), | ||
| detachedHtmlCanvas: context.canvas instanceof HTMLCanvasElement && !context.canvas.isConnected, | ||
| } | ||
| }) | ||
| expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true }) | ||
| }) | ||
|
|
||
| it('falls back to HTML WebGL when a native canvas only supports 2D', async () => { | ||
| const { outputFiles } = await build({ | ||
| stdin: { | ||
| contents: "export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas'", | ||
| resolveDir: __dirname, | ||
| }, | ||
| bundle: true, | ||
| globalName: 'h5Canvas', | ||
| write: false, | ||
| }) | ||
| const page = await newE2EPage() | ||
| await page.addScriptTag({ content: outputFiles[0].text }) | ||
| const result = await page.evaluate(() => { | ||
| class PartialOffscreenCanvas { | ||
| getContext () { return null } | ||
| } | ||
| Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: PartialOffscreenCanvas }) | ||
| const { h5Canvas } = window as unknown as { | ||
| h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas') | ||
| } | ||
| const canvas = h5Canvas.createOffscreenCanvas({ type: 'webgl', width: 1, height: 1 }) | ||
| const gl = canvas.getContext('webgl') | ||
| if (!gl) throw new Error('WebGL is unavailable') | ||
| gl.clearColor(1, 0, 0, 1) | ||
| gl.clear(gl.COLOR_BUFFER_BIT) | ||
| const pixel = new Uint8Array(4) | ||
| gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel) | ||
| return { | ||
| pixel: Array.from(pixel), | ||
| detachedHtmlCanvas: gl.canvas instanceof HTMLCanvasElement && !gl.canvas.isConnected, | ||
| } | ||
| }) | ||
| expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import Taro from '@tarojs/taro' | ||
|
|
||
| import type {} from '../../types/h5' | ||
|
|
||
| export async function drawWithPublicApi (url: string) { | ||
| const canvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 }) | ||
| const context = canvas.getContext('2d') | ||
| // @ts-expect-error H5 contexts can be unavailable. | ||
| context.clearRect(0, 0, 300, 150) | ||
| if (!context) return | ||
| const image = canvas.createImage() | ||
| image.onload = null | ||
| image.onerror = null | ||
| await new Promise<void>((resolve, reject) => { | ||
| image.onload = () => resolve() | ||
| image.onerror = reject | ||
| image.src = url | ||
| }) | ||
| context.clearRect(0, 0, 300, 150) | ||
| context.drawImage(image, 0, 0) | ||
| return context.getImageData(0, 0, 300, 150) | ||
| } | ||
| const gl = Taro.createOffscreenCanvas({ type: 'webgl' }).getContext('webgl') | ||
| if (gl) gl.clear(gl.COLOR_BUFFER_BIT) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import { createOffscreenCanvas } from '@tarojs/taro-h5' | ||
|
|
||
| describe('createOffscreenCanvas', () => { | ||
| const original = Object.getOwnPropertyDescriptor(globalThis, 'OffscreenCanvas') | ||
|
|
||
| afterEach(() => { | ||
| if (original) Object.defineProperty(globalThis, 'OffscreenCanvas', original) | ||
| else Reflect.deleteProperty(globalThis, 'OffscreenCanvas') | ||
| jest.restoreAllMocks() | ||
| }) | ||
|
|
||
| it('keeps dimensions and context on the native canvas', () => { | ||
| const context = {} | ||
| const backing = { width: 0, height: 0, getContext: jest.fn().mockReturnValue(context) } | ||
| const native = jest.fn().mockReturnValue(backing) | ||
| Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native }) | ||
|
|
||
| const canvas = createOffscreenCanvas({ type: '2d', width: 20, height: 10 }) | ||
| expect(native).toHaveBeenCalledWith(20, 10) | ||
| expect(canvas.height).toBe(10) | ||
| canvas.width = 30 | ||
| expect(backing.width).toBe(30) | ||
| expect(canvas.getContext('webgl')).toBeNull() | ||
| expect(canvas.getContext('2d')).toBe(context) | ||
| expect(backing.getContext).toHaveBeenCalledTimes(2) | ||
| expect(canvas.createImage()).toBeInstanceOf(HTMLImageElement) | ||
| }) | ||
|
|
||
| it('falls back when the native canvas cannot provide the requested WebGL context', () => { | ||
| const nativeContext = jest.fn().mockReturnValue(null) | ||
| const native = jest.fn().mockImplementation(() => ({ getContext: nativeContext })) | ||
| Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native }) | ||
| const context = { clear: jest.fn() } | ||
| const htmlContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as unknown as WebGLRenderingContext) | ||
| const canvas = createOffscreenCanvas({ type: 'webgl', width: 40, height: 30 }) | ||
| expect(nativeContext).toHaveBeenCalledWith('webgl') | ||
| expect(canvas.getContext('webgl')).toBe(context) | ||
| expect(canvas.getContext('2d')).toBeNull() | ||
| expect([canvas.width, canvas.height]).toEqual([40, 30]) | ||
| expect((htmlContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false) | ||
| }) | ||
|
|
||
| it('falls back to a detached HTML canvas and defaults to WebGL', () => { | ||
| Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: undefined }) | ||
| const getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null) | ||
| const canvas = createOffscreenCanvas({}) | ||
| expect([canvas.width, canvas.height]).toEqual([300, 150]) | ||
| expect(canvas.getContext('webgl')).toBeNull() | ||
| expect(getContext).toHaveBeenCalledWith('webgl') | ||
| expect((getContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import { resolve } from 'node:path' | ||
|
|
||
| import * as ts from 'typescript' | ||
|
|
||
| it.each(['offscreen.types.ts', 'offscreen.h5.types.ts'])('compiles %s under strict null checking', filename => { | ||
| const fixture = resolve(__dirname, filename) | ||
| const program = ts.createProgram([fixture], { | ||
| noEmit: true, | ||
| strictNullChecks: true, | ||
| skipLibCheck: true, | ||
| esModuleInterop: true, | ||
| target: ts.ScriptTarget.ES2020, | ||
| module: ts.ModuleKind.CommonJS, | ||
| types: [], | ||
| }) | ||
| const source = program.getSourceFile(fixture)! | ||
| const diagnostics = [ | ||
| ...program.getSyntacticDiagnostics(source), | ||
| ...program.getSemanticDiagnostics(source), | ||
| ] | ||
| expect(diagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([]) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import Taro from '@tarojs/taro' | ||
|
|
||
| import { createOffscreenCanvas } from '../../src/index' | ||
|
|
||
| declare function acceptContext(context: Taro.RenderingContext): void | ||
| declare function acceptHandler(handler: (...args: any[]) => any): void | ||
| declare const ordinaryCanvas: Taro.Canvas | ||
|
|
||
| const miniCanvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 }) | ||
| acceptContext(miniCanvas.getContext('2d')) | ||
| acceptHandler(miniCanvas.createImage().onload) | ||
| acceptHandler(miniCanvas.createImage().onerror) | ||
| acceptHandler(ordinaryCanvas.createImage().onload) | ||
| acceptHandler(ordinaryCanvas.createImage().onerror) | ||
|
|
||
| export async function drawImage (url: string) { | ||
| const canvas = createOffscreenCanvas({ type: '2d', width: 300, height: 150 }) | ||
| const context = canvas.getContext('2d') | ||
| // @ts-expect-error H5 callers must check for an unavailable context. | ||
| context.clearRect(0, 0, 300, 150) | ||
| if (!context) throw new Error('2D context is unavailable') | ||
|
|
||
| const image = canvas.createImage() | ||
| const initialOnload: typeof image.onload = null | ||
| const initialOnerror: typeof image.onerror = null | ||
| image.onload = initialOnload | ||
| image.onerror = initialOnerror | ||
| await new Promise<void>((resolve, reject) => { | ||
| image.onload = () => resolve() | ||
| image.onerror = reject | ||
| image.src = url | ||
| }) | ||
| context.clearRect(0, 0, 300, 150) | ||
| context.drawImage(image, 0, 0) | ||
| return context.getImageData(0, 0, 300, 150) | ||
| } | ||
|
|
||
| const gl = createOffscreenCanvas({ type: 'webgl' }).getContext('webgl') | ||
| if (gl) gl.clear(gl.COLOR_BUFFER_BIT) |
25 changes: 25 additions & 0 deletions
25
packages/taro-h5/integration/canvas/offscreen.harmony.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import Taro from '@tarojs/api' | ||
|
|
||
| import { loadHarmonyApi } from '../helpers/loadHarmonyApi' | ||
|
|
||
| afterEach(() => jest.restoreAllMocks()) | ||
|
|
||
| it('keeps the Harmony Hybrid createOffscreenCanvas placeholder at the public entry', async () => { | ||
| jest.replaceProperty(process.env, 'NODE_ENV', 'production') | ||
| jest.spyOn(console, 'warn').mockImplementation(() => {}) | ||
| const createElement = jest.spyOn(document, 'createElement') | ||
| const unsupported = jest.fn() | ||
| const createOffscreenCanvas = await loadHarmonyApi('createOffscreenCanvas') | ||
| const options = { type: '2d' as const, width: 20, height: 10 } | ||
|
|
||
| Taro.eventCenter.on('__taroNotSupport', unsupported) | ||
| try { | ||
| await expect(createOffscreenCanvas(options)).resolves.toEqual({ errMsg: '暂时不支持 API' }) | ||
| expect(unsupported).toHaveBeenCalledWith({ | ||
| name: 'createOffscreenCanvas', args: [options], type: 'method', category: 'temporarily', | ||
| }) | ||
| expect(createElement).not.toHaveBeenCalled() | ||
| } finally { | ||
| Taro.eventCenter.off('__taroNotSupport', unsupported) | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import { existsSync } from 'node:fs' | ||
| import { isAbsolute, resolve } from 'node:path' | ||
| import { runInNewContext } from 'node:vm' | ||
|
|
||
| import { rollup } from 'rollup' | ||
|
|
||
| import type Taro from '@tarojs/api' | ||
|
|
||
| /** Import a named API from the generated public entry through a real Rollup consumer. */ | ||
| export async function loadHarmonyApi<K extends keyof typeof Taro> (name: K): Promise<(typeof Taro)[K]> { | ||
| const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js') | ||
| if (!existsSync(publicApi)) { | ||
| throw new Error('Build Harmony Hybrid first, or run pnpm --filter @tarojs/taro-h5 test:integration') | ||
| } | ||
| const consumer = '\0harmony-api-consumer' | ||
| const bundle = await rollup({ | ||
| input: consumer, | ||
| external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id), | ||
| treeshake: { moduleSideEffects: false }, | ||
| plugins: [{ | ||
| name: 'harmony-api-consumer', | ||
| resolveId: id => id === consumer ? id : null, | ||
| load: id => id === consumer ? `export { ${String(name)} } from ${JSON.stringify(publicApi)}` : null, | ||
| }], | ||
| }) | ||
| const exports: Pick<typeof Taro, K> = Object.create(null) | ||
| try { | ||
| const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' }) | ||
| runInNewContext(output[0].code, { exports, require, process, console, document, window }) | ||
| return exports[name] | ||
| } finally { | ||
| await bundle.close() | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import Taro from '@tarojs/api' | ||
|
|
||
| import type { H5OffscreenCanvas } from '../../../types/canvas' | ||
|
|
||
| export type { H5OffscreenCanvas } from '../../../types/canvas' | ||
|
|
||
| type ContextType = '2d' | 'webgl' | ||
| type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | ||
|
|
||
| export const createOffscreenCanvas = ({ | ||
| type = 'webgl', | ||
| width = 300, | ||
| height = 150, | ||
| }: Taro.createOffscreenCanvas.Option = {}): H5OffscreenCanvas => { | ||
| if (type !== '2d' && type !== 'webgl') { | ||
| throw new TypeError('createOffscreenCanvas: expected type to be 2d or webgl') | ||
| } | ||
|
|
||
| const hasNativeCanvas = typeof OffscreenCanvas === 'function' | ||
| let canvas = hasNativeCanvas | ||
| ? new OffscreenCanvas(width, height) | ||
| : document.createElement('canvas') | ||
| canvas.width = width | ||
| canvas.height = height | ||
|
|
||
| if (hasNativeCanvas && | ||
| !(type === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl'))) { | ||
| canvas = document.createElement('canvas') | ||
| canvas.width = width | ||
| canvas.height = height | ||
| } | ||
|
|
||
| function getContext (contextType: '2d'): Context2D | null | ||
| function getContext (contextType: 'webgl'): WebGLRenderingContext | null | ||
| function getContext (contextType: ContextType): Context2D | WebGLRenderingContext | null | ||
| function getContext (contextType: ContextType) { | ||
| if (contextType !== type) return null | ||
| return contextType === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl') | ||
| } | ||
|
|
||
| return { | ||
| get width () { return canvas.width }, | ||
| set width (value) { canvas.width = value }, | ||
| get height () { return canvas.height }, | ||
| set height (value) { canvas.height = value }, | ||
| createImage: () => new Image(), | ||
| getContext, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| /** Browser-backed offscreen canvas. A requested context can be unavailable. */ | ||
| export interface H5OffscreenCanvas { | ||
| width: number | ||
| height: number | ||
| createImage(): HTMLImageElement | ||
| getContext(contextType: '2d'): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null | ||
| getContext(contextType: 'webgl'): WebGLRenderingContext | null | ||
| getContext(contextType: '2d' | 'webgl'): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | WebGLRenderingContext | null | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import Taro from '@tarojs/taro' | ||
|
|
||
| import type { H5OffscreenCanvas } from './canvas' | ||
|
|
||
| /** Opt in through the H5 tsconfig's types or a triple-slash reference. */ | ||
| declare module '@tarojs/taro' { | ||
| interface TaroStatic { | ||
| createOffscreenCanvas(options: Taro.createOffscreenCanvas.Option): H5OffscreenCanvas | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.