From 11eee51cbae707d5f8f55653dcb030ce804928e8 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Sat, 14 Nov 2026 04:19:47 +0800 Subject: [PATCH 1/3] feat(h5): support creating an offscreen canvas --- .../__tests__/canvas/offscreen.test.ts | 38 +++++++++++++++++++ .../src/api/canvas/createOffscreenCanvas.ts | 29 ++++++++++++++ packages/taro-h5/src/api/canvas/index.ts | 4 +- packages/taro/types/api/canvas/index.d.ts | 17 +++++---- 4 files changed, 77 insertions(+), 11 deletions(-) create mode 100644 packages/taro-h5/__tests__/canvas/offscreen.test.ts create mode 100644 packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts diff --git a/packages/taro-h5/__tests__/canvas/offscreen.test.ts b/packages/taro-h5/__tests__/canvas/offscreen.test.ts new file mode 100644 index 000000000000..91e57618071b --- /dev/null +++ b/packages/taro-h5/__tests__/canvas/offscreen.test.ts @@ -0,0 +1,38 @@ +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(1) + expect(canvas.createImage()).toBeInstanceOf(HTMLImageElement) + }) + + 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) + }) +}) diff --git a/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts new file mode 100644 index 000000000000..8b2797b4ef9c --- /dev/null +++ b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts @@ -0,0 +1,29 @@ +import Taro from '@tarojs/api' + +export const createOffscreenCanvas: typeof Taro.createOffscreenCanvas = ({ + type = 'webgl', + width = 300, + height = 150, +} = {}) => { + if (type !== '2d' && type !== 'webgl') { + throw new TypeError('createOffscreenCanvas: expected type to be 2d or webgl') + } + + const canvas = typeof OffscreenCanvas === 'function' + ? new OffscreenCanvas(width, height) + : document.createElement('canvas') + canvas.width = width + canvas.height = height + + 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 (contextType) { + if (contextType !== type) return null + return contextType === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl') + }, + } +} diff --git a/packages/taro-h5/src/api/canvas/index.ts b/packages/taro-h5/src/api/canvas/index.ts index 0958f1c1f4ae..427f926dde2f 100644 --- a/packages/taro-h5/src/api/canvas/index.ts +++ b/packages/taro-h5/src/api/canvas/index.ts @@ -1,9 +1,7 @@ -import { temporarilyNotSupport } from '../../utils' - // 画布 /** 创建离屏 canvas 实例 */ -export const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas') +export * from './createOffscreenCanvas' /** 创建 canvas 的绘图上下文 CanvasContext 对象 */ export * from './createCanvasContext' diff --git a/packages/taro/types/api/canvas/index.d.ts b/packages/taro/types/api/canvas/index.d.ts index df65774034ad..433fea2280bd 100644 --- a/packages/taro/types/api/canvas/index.d.ts +++ b/packages/taro/types/api/canvas/index.d.ts @@ -1824,9 +1824,9 @@ declare module '../../index' { */ referrerPolicy: string /** 图片加载发生错误后触发的回调函数 */ - onerror: (...args: any[]) => any + onerror: ((...args: any[]) => any) | null /** 图片加载完成后触发的回调函数 */ - onload: (...args: any[]) => any + onload: ((...args: any[]) => any) | null } /** ImageData 对象 @@ -1843,7 +1843,7 @@ declare module '../../index' { } /** 离屏 canvas 实例,可通过 Taro.createOffscreenCanvas 创建。 - * @supported weapp + * @supported weapp, h5 * @see https://developers.weixin.qq.com/miniprogram/dev/api/canvas/OffscreenCanvas.html */ interface OffscreenCanvas { @@ -1854,17 +1854,17 @@ declare module '../../index' { /** 创建一个图片对象。支持在 2D Canvas 和 WebGL Canvas 下使用, 但不支持混用 2D 和 WebGL 的方法 * * > 注意不允许混用 webgl 和 2d 画布创建的图片对象,使用时请注意尽量使用 canvas 自身的 createImage 创建图片对象。 - * @supported weapp + * @supported weapp, h5 * @see https://developers.weixin.qq.com/miniprogram/dev/api/canvas/OffscreenCanvas.createImage.html */ createImage(): Image /** 该方法返回 OffscreenCanvas 的绘图上下文 * - * > 当前仅支持获取 WebGL 绘图上下文 - * @supported weapp, tt + * H5 返回浏览器的绘图上下文,无法创建时返回 null。 + * @supported weapp, tt, h5 * @see https://developers.weixin.qq.com/miniprogram/dev/api/canvas/OffscreenCanvas.getContext.html */ - getContext(contextType: 'webgl' | '2d'): RenderingContext + getContext(contextType: 'webgl' | '2d'): RenderingContext | null } /** Canvas 2D API 的接口 Path2D 用来声明路径,此路径稍后会被CanvasRenderingContext2D 对象使用。CanvasRenderingContext2D 接口的 路径方法 也存在于 Path2D 这个接口中,允许你在 canvas 中根据需要创建可以保留并重用的路径。 @@ -2013,7 +2013,8 @@ declare module '../../index' { interface TaroStatic { /** 创建离屏 canvas 实例 - * @supported weapp, tt + * H5 在页面中调用,默认尺寸为 300×150,可用时使用浏览器 OffscreenCanvas。 + * @supported weapp, tt, h5 * @example * ```tsx * // 创建离屏 2D canvas 实例 From 9609367f406b850ab2a4cfdf2306efe31605b9d4 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 24 Nov 2026 20:16:40 +0800 Subject: [PATCH 2/3] fix(h5): preserve canvas types across platforms --- .../__tests__/offscreen-canvas.e2e.ts | 41 +++++++++++++++++++ .../canvas/offscreen.harmony.test.ts | 25 +++++++++++ .../__tests__/canvas/offscreen.types.test.ts | 22 ++++++++++ .../__tests__/canvas/offscreen.types.ts | 39 ++++++++++++++++++ .../__tests__/helpers/loadHarmonyApi.ts | 30 ++++++++++++++ .../src/api/canvas/createOffscreenCanvas.ts | 30 +++++++++++--- .../src/api/apis/canvas/index.ts | 4 +- .../src/api/apis/comments.ts | 6 --- packages/taro/types/api/canvas/index.d.ts | 19 +++++---- 9 files changed, 196 insertions(+), 20 deletions(-) create mode 100644 packages/taro-components/__tests__/offscreen-canvas.e2e.ts create mode 100644 packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts create mode 100644 packages/taro-h5/__tests__/canvas/offscreen.types.test.ts create mode 100644 packages/taro-h5/__tests__/canvas/offscreen.types.ts create mode 100644 packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts diff --git a/packages/taro-components/__tests__/offscreen-canvas.e2e.ts b/packages/taro-components/__tests__/offscreen-canvas.e2e.ts new file mode 100644 index 000000000000..dc4760ed8766 --- /dev/null +++ b/packages/taro-components/__tests__/offscreen-canvas.e2e.ts @@ -0,0 +1,41 @@ +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((resolve, reject) => { + image.onload = () => resolve() + image.onerror = reject + image.src = 'data:image/svg+xml,' + }) + 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 }) +}) diff --git a/packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts b/packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts new file mode 100644 index 000000000000..e69630e165b2 --- /dev/null +++ b/packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts @@ -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) + } +}) diff --git a/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts b/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts new file mode 100644 index 000000000000..9df4206912d6 --- /dev/null +++ b/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts @@ -0,0 +1,22 @@ +import { resolve } from 'node:path' + +import * as ts from 'typescript' + +it('compiles platform-specific canvas signatures under strict null checking', () => { + const fixture = resolve(__dirname, 'offscreen.types.ts') + 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([]) +}) diff --git a/packages/taro-h5/__tests__/canvas/offscreen.types.ts b/packages/taro-h5/__tests__/canvas/offscreen.types.ts new file mode 100644 index 000000000000..227d5d4163d8 --- /dev/null +++ b/packages/taro-h5/__tests__/canvas/offscreen.types.ts @@ -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((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) diff --git a/packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts b/packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts new file mode 100644 index 000000000000..f3322f4a019d --- /dev/null +++ b/packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts @@ -0,0 +1,30 @@ +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 (name: K): Promise<(typeof Taro)[K]> { + const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js') + 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 = 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() + } +} diff --git a/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts index 8b2797b4ef9c..71fba060bd72 100644 --- a/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts +++ b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts @@ -1,10 +1,23 @@ import Taro from '@tarojs/api' -export const createOffscreenCanvas: typeof Taro.createOffscreenCanvas = ({ +type ContextType = '2d' | 'webgl' +type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D + +/** The browser-backed canvas returned by the named H5 API. */ +export interface H5OffscreenCanvas { + width: number + height: number + createImage(): HTMLImageElement + getContext(contextType: '2d'): Context2D | null + getContext(contextType: 'webgl'): WebGLRenderingContext | null + getContext(contextType: ContextType): Context2D | WebGLRenderingContext | null +} + +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') } @@ -15,15 +28,20 @@ export const createOffscreenCanvas: typeof Taro.createOffscreenCanvas = ({ 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 (contextType) { - if (contextType !== type) return null - return contextType === '2d' ? canvas.getContext('2d') : canvas.getContext('webgl') - }, + getContext, } } diff --git a/packages/taro-platform-harmony-hybrid/src/api/apis/canvas/index.ts b/packages/taro-platform-harmony-hybrid/src/api/apis/canvas/index.ts index 32bb19421d75..334634933d4a 100644 --- a/packages/taro-platform-harmony-hybrid/src/api/apis/canvas/index.ts +++ b/packages/taro-platform-harmony-hybrid/src/api/apis/canvas/index.ts @@ -1,9 +1,11 @@ +import { temporarilyNotSupport } from '../utils' + /** * 创建离屏 canvas 实例 * * @canNotUse createOffscreenCanvas */ -export { createOffscreenCanvas } from '@tarojs/taro-h5' +export const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas') /** 创建 canvas 的绘图上下文 CanvasContext 对象 */ export * from './createCanvasContext' diff --git a/packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts b/packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts index 3e68b6b0db70..8741463b2e90 100644 --- a/packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts +++ b/packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts @@ -547,12 +547,6 @@ * @canNotUse createMediaRecorder */ -/** - * 创建离屏 canvas 实例 - * - * @canNotUse createOffscreenCanvas - */ - /** * 创建激励视频广告组件 * diff --git a/packages/taro/types/api/canvas/index.d.ts b/packages/taro/types/api/canvas/index.d.ts index 433fea2280bd..eed87883afae 100644 --- a/packages/taro/types/api/canvas/index.d.ts +++ b/packages/taro/types/api/canvas/index.d.ts @@ -1824,9 +1824,9 @@ declare module '../../index' { */ referrerPolicy: string /** 图片加载发生错误后触发的回调函数 */ - onerror: ((...args: any[]) => any) | null + onerror: (...args: any[]) => any /** 图片加载完成后触发的回调函数 */ - onload: ((...args: any[]) => any) | null + onload: (...args: any[]) => any } /** ImageData 对象 @@ -1864,7 +1864,7 @@ declare module '../../index' { * @supported weapp, tt, h5 * @see https://developers.weixin.qq.com/miniprogram/dev/api/canvas/OffscreenCanvas.getContext.html */ - getContext(contextType: 'webgl' | '2d'): RenderingContext | null + getContext(contextType: 'webgl' | '2d'): RenderingContext } /** Canvas 2D API 的接口 Path2D 用来声明路径,此路径稍后会被CanvasRenderingContext2D 对象使用。CanvasRenderingContext2D 接口的 路径方法 也存在于 Path2D 这个接口中,允许你在 canvas 中根据需要创建可以保留并重用的路径。 @@ -2014,19 +2014,24 @@ declare module '../../index' { interface TaroStatic { /** 创建离屏 canvas 实例 * H5 在页面中调用,默认尺寸为 300×150,可用时使用浏览器 OffscreenCanvas。 + * 从 `@tarojs/taro-h5` 导入同名函数可获得 H5 专用的绘图上下文和图片类型。 * @supported weapp, tt, h5 * @example * ```tsx - * // 创建离屏 2D canvas 实例 - * const canvas = Taro.createOffscreenCanvas({type: '2d', width: 300, height: 150}) + * // H5 + * import { createOffscreenCanvas } from '@tarojs/taro-h5' + * + * const canvas = createOffscreenCanvas({type: '2d', width: 300, height: 150}) * // 获取 context。注意这里必须要与创建时的 type 一致 * const context = canvas.getContext('2d') + * if (!context) throw new Error('2D context is unavailable') * * // 创建一个图片 * const image = canvas.createImage() * // 等待图片加载 - * await new Promise(resolve => { - * image.onload = resolve + * await new Promise((resolve, reject) => { + * image.onload = () => resolve() + * image.onerror = reject * image.src = IMAGE_URL // 要加载的图片 url * }) * From 1e70c280f5bd4ab6ea8bb10f0b8f6fc615dd520c Mon Sep 17 00:00:00 2001 From: Jarvis Date: Sun, 29 Nov 2026 17:13:39 +0800 Subject: [PATCH 3/3] fix(h5): handle partial offscreen canvas support and public types --- .github/workflows/nodejs.yml | 5 +++ .../__tests__/offscreen-canvas.e2e.ts | 35 +++++++++++++++++++ packages/taro-h5/README.md | 10 ++++++ .../__tests__/canvas/offscreen.h5.types.ts | 24 +++++++++++++ .../__tests__/canvas/offscreen.test.ts | 16 ++++++++- .../__tests__/canvas/offscreen.types.test.ts | 4 +-- .../canvas/offscreen.harmony.test.ts | 0 .../helpers/loadHarmonyApi.ts | 4 +++ packages/taro-h5/package.json | 1 + .../src/api/canvas/createOffscreenCanvas.ts | 24 +++++++------ packages/taro-h5/types/canvas.d.ts | 9 +++++ packages/taro-h5/types/h5.d.ts | 10 ++++++ packages/taro/types/api/canvas/index.d.ts | 8 ++--- 13 files changed, 132 insertions(+), 18 deletions(-) create mode 100644 packages/taro-h5/__tests__/canvas/offscreen.h5.types.ts rename packages/taro-h5/{__tests__ => integration}/canvas/offscreen.harmony.test.ts (100%) rename packages/taro-h5/{__tests__ => integration}/helpers/loadHarmonyApi.ts (87%) create mode 100644 packages/taro-h5/types/canvas.d.ts create mode 100644 packages/taro-h5/types/h5.d.ts diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 91286544a931..a607e49e348a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -120,6 +120,11 @@ jobs: else pnpm test fi + - name: H5 Harmony Hybrid integration + shell: bash + run: pnpm --filter @tarojs/taro-h5 run test:integration + env: + NODE_OPTIONS: --max_old_space_size=4096 # 以下 coverage 流程通过 artifact 拆分文件作为单独 job 上传时间损耗过长,因此在在 node test 后直接继续执行 - name: Upload [taro-cli] coverage to Codecov uses: codecov/codecov-action@v5 diff --git a/packages/taro-components/__tests__/offscreen-canvas.e2e.ts b/packages/taro-components/__tests__/offscreen-canvas.e2e.ts index dc4760ed8766..4623f03a2dce 100644 --- a/packages/taro-components/__tests__/offscreen-canvas.e2e.ts +++ b/packages/taro-components/__tests__/offscreen-canvas.e2e.ts @@ -39,3 +39,38 @@ it('draws an image and reads its pixel with the H5 HTML canvas fallback', async }) 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 }) +}) diff --git a/packages/taro-h5/README.md b/packages/taro-h5/README.md index 332eaa7bb36e..6cecf46cc818 100644 --- a/packages/taro-h5/README.md +++ b/packages/taro-h5/README.md @@ -3,3 +3,13 @@ 暴露给 `@tarojs/taro` 的 H5 端 API。 需要配合 `babel-plugin-transform-taroapi` 才能使用 ES6 default import 的语法,相关配置详情在 `babel-preset-taro` 中。 + +## H5 离屏画布类型 + +H5 项目通过 `@tarojs/taro` 调用离屏画布时,可在 H5 专用 tsconfig 的 `compilerOptions.types` 中加入 `@tarojs/taro-h5/types/h5`,或在 H5 专用声明文件中引用: + +```ts +/// +``` + +此入口为 `Taro.createOffscreenCanvas().getContext()` 提供可空的浏览器 2D/WebGL 类型。调用方应先判断上下文是否存在。小程序项目继续使用默认类型入口。 diff --git a/packages/taro-h5/__tests__/canvas/offscreen.h5.types.ts b/packages/taro-h5/__tests__/canvas/offscreen.h5.types.ts new file mode 100644 index 000000000000..fcdc2583a9d3 --- /dev/null +++ b/packages/taro-h5/__tests__/canvas/offscreen.h5.types.ts @@ -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((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) diff --git a/packages/taro-h5/__tests__/canvas/offscreen.test.ts b/packages/taro-h5/__tests__/canvas/offscreen.test.ts index 91e57618071b..441749b02659 100644 --- a/packages/taro-h5/__tests__/canvas/offscreen.test.ts +++ b/packages/taro-h5/__tests__/canvas/offscreen.test.ts @@ -22,10 +22,24 @@ describe('createOffscreenCanvas', () => { expect(backing.width).toBe(30) expect(canvas.getContext('webgl')).toBeNull() expect(canvas.getContext('2d')).toBe(context) - expect(backing.getContext).toHaveBeenCalledTimes(1) + 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) diff --git a/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts b/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts index 9df4206912d6..bd7eaaf42689 100644 --- a/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts +++ b/packages/taro-h5/__tests__/canvas/offscreen.types.test.ts @@ -2,8 +2,8 @@ import { resolve } from 'node:path' import * as ts from 'typescript' -it('compiles platform-specific canvas signatures under strict null checking', () => { - const fixture = resolve(__dirname, 'offscreen.types.ts') +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, diff --git a/packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts b/packages/taro-h5/integration/canvas/offscreen.harmony.test.ts similarity index 100% rename from packages/taro-h5/__tests__/canvas/offscreen.harmony.test.ts rename to packages/taro-h5/integration/canvas/offscreen.harmony.test.ts diff --git a/packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts b/packages/taro-h5/integration/helpers/loadHarmonyApi.ts similarity index 87% rename from packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts rename to packages/taro-h5/integration/helpers/loadHarmonyApi.ts index f3322f4a019d..938b59aaacd0 100644 --- a/packages/taro-h5/__tests__/helpers/loadHarmonyApi.ts +++ b/packages/taro-h5/integration/helpers/loadHarmonyApi.ts @@ -1,3 +1,4 @@ +import { existsSync } from 'node:fs' import { isAbsolute, resolve } from 'node:path' import { runInNewContext } from 'node:vm' @@ -8,6 +9,9 @@ import type Taro from '@tarojs/api' /** Import a named API from the generated public entry through a real Rollup consumer. */ export async function loadHarmonyApi (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, diff --git a/packages/taro-h5/package.json b/packages/taro-h5/package.json index 24a4173585b9..8a753ded5279 100644 --- a/packages/taro-h5/package.json +++ b/packages/taro-h5/package.json @@ -26,6 +26,7 @@ "rollup": "rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript --bundleConfigAsCjs", "test": "jest", "test:ci": "jest --ci -i --coverage --silent", + "test:integration": "pnpm run build && pnpm --filter @tarojs/plugin-platform-harmony-hybrid run build && jest --ci -i --testMatch \"**/integration/**/*.test.ts\"", "test:dev": "jest --watch", "test:coverage": "jest --coverage" }, diff --git a/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts index 71fba060bd72..9992de37a869 100644 --- a/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts +++ b/packages/taro-h5/src/api/canvas/createOffscreenCanvas.ts @@ -1,18 +1,12 @@ 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 -/** The browser-backed canvas returned by the named H5 API. */ -export interface H5OffscreenCanvas { - width: number - height: number - createImage(): HTMLImageElement - getContext(contextType: '2d'): Context2D | null - getContext(contextType: 'webgl'): WebGLRenderingContext | null - getContext(contextType: ContextType): Context2D | WebGLRenderingContext | null -} - export const createOffscreenCanvas = ({ type = 'webgl', width = 300, @@ -22,12 +16,20 @@ export const createOffscreenCanvas = ({ throw new TypeError('createOffscreenCanvas: expected type to be 2d or webgl') } - const canvas = typeof OffscreenCanvas === 'function' + 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 diff --git a/packages/taro-h5/types/canvas.d.ts b/packages/taro-h5/types/canvas.d.ts new file mode 100644 index 000000000000..5626595927df --- /dev/null +++ b/packages/taro-h5/types/canvas.d.ts @@ -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 +} diff --git a/packages/taro-h5/types/h5.d.ts b/packages/taro-h5/types/h5.d.ts new file mode 100644 index 000000000000..0c79dd87b619 --- /dev/null +++ b/packages/taro-h5/types/h5.d.ts @@ -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 + } +} diff --git a/packages/taro/types/api/canvas/index.d.ts b/packages/taro/types/api/canvas/index.d.ts index eed87883afae..e89a35465d5b 100644 --- a/packages/taro/types/api/canvas/index.d.ts +++ b/packages/taro/types/api/canvas/index.d.ts @@ -2014,14 +2014,14 @@ declare module '../../index' { interface TaroStatic { /** 创建离屏 canvas 实例 * H5 在页面中调用,默认尺寸为 300×150,可用时使用浏览器 OffscreenCanvas。 - * 从 `@tarojs/taro-h5` 导入同名函数可获得 H5 专用的绘图上下文和图片类型。 + * H5 公共入口的专用类型可通过 `@tarojs/taro-h5/types/h5` 启用,也可从 `@tarojs/taro-h5` 导入同名函数。 * @supported weapp, tt, h5 * @example * ```tsx - * // H5 - * import { createOffscreenCanvas } from '@tarojs/taro-h5' + * /// + * import Taro from '@tarojs/taro' * - * const canvas = createOffscreenCanvas({type: '2d', width: 300, height: 150}) + * const canvas = Taro.createOffscreenCanvas({type: '2d', width: 300, height: 150}) * // 获取 context。注意这里必须要与创建时的 type 一致 * const context = canvas.getContext('2d') * if (!context) throw new Error('2D context is unavailable')