Skip to content

Commit 3532ac9

Browse files
authored
feat(h5): 支持 createOffscreenCanvas (#19674)
* feat(h5): support creating an offscreen canvas * fix(h5): preserve canvas types across platforms * fix(h5): handle partial offscreen canvas support and public types
1 parent b307184 commit 3532ac9

17 files changed

Lines changed: 374 additions & 18 deletions

File tree

‎.github/workflows/nodejs.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,11 @@ jobs:
120120
else
121121
pnpm test
122122
fi
123+
- name: H5 Harmony Hybrid integration
124+
shell: bash
125+
run: pnpm --filter @tarojs/taro-h5 run test:integration
126+
env:
127+
NODE_OPTIONS: --max_old_space_size=4096
123128
# 以下 coverage 流程通过 artifact 拆分文件作为单独 job 上传时间损耗过长,因此在在 node test 后直接继续执行
124129
- name: Upload [taro-cli] coverage to Codecov
125130
uses: codecov/codecov-action@v5
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { newE2EPage } from '@stencil/core/testing'
2+
import { build } from 'esbuild'
3+
4+
it('draws an image and reads its pixel with the H5 HTML canvas fallback', async () => {
5+
const { outputFiles } = await build({
6+
stdin: {
7+
contents: `
8+
export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas'
9+
`,
10+
resolveDir: __dirname,
11+
},
12+
bundle: true,
13+
globalName: 'h5Canvas',
14+
write: false,
15+
})
16+
const page = await newE2EPage()
17+
await page.addScriptTag({ content: outputFiles[0].text })
18+
const result = await page.evaluate(async () => {
19+
Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: undefined })
20+
const { h5Canvas } = window as unknown as {
21+
h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas')
22+
}
23+
const canvas = h5Canvas.createOffscreenCanvas({ type: '2d', width: 1, height: 1 })
24+
const context = canvas.getContext('2d')
25+
if (!context) throw new Error('2D context is unavailable')
26+
27+
const image = canvas.createImage()
28+
await new Promise<void>((resolve, reject) => {
29+
image.onload = () => resolve()
30+
image.onerror = reject
31+
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>'
32+
})
33+
context.clearRect(0, 0, 1, 1)
34+
context.drawImage(image, 0, 0)
35+
return {
36+
pixel: Array.from(context.getImageData(0, 0, 1, 1).data),
37+
detachedHtmlCanvas: context.canvas instanceof HTMLCanvasElement && !context.canvas.isConnected,
38+
}
39+
})
40+
expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true })
41+
})
42+
43+
it('falls back to HTML WebGL when a native canvas only supports 2D', async () => {
44+
const { outputFiles } = await build({
45+
stdin: {
46+
contents: "export { createOffscreenCanvas } from '../../taro-h5/src/api/canvas/createOffscreenCanvas'",
47+
resolveDir: __dirname,
48+
},
49+
bundle: true,
50+
globalName: 'h5Canvas',
51+
write: false,
52+
})
53+
const page = await newE2EPage()
54+
await page.addScriptTag({ content: outputFiles[0].text })
55+
const result = await page.evaluate(() => {
56+
class PartialOffscreenCanvas {
57+
getContext () { return null }
58+
}
59+
Object.defineProperty(window, 'OffscreenCanvas', { configurable: true, value: PartialOffscreenCanvas })
60+
const { h5Canvas } = window as unknown as {
61+
h5Canvas: typeof import('../../taro-h5/src/api/canvas/createOffscreenCanvas')
62+
}
63+
const canvas = h5Canvas.createOffscreenCanvas({ type: 'webgl', width: 1, height: 1 })
64+
const gl = canvas.getContext('webgl')
65+
if (!gl) throw new Error('WebGL is unavailable')
66+
gl.clearColor(1, 0, 0, 1)
67+
gl.clear(gl.COLOR_BUFFER_BIT)
68+
const pixel = new Uint8Array(4)
69+
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel)
70+
return {
71+
pixel: Array.from(pixel),
72+
detachedHtmlCanvas: gl.canvas instanceof HTMLCanvasElement && !gl.canvas.isConnected,
73+
}
74+
})
75+
expect(result).toEqual({ pixel: [255, 0, 0, 255], detachedHtmlCanvas: true })
76+
})

‎packages/taro-h5/README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,13 @@
33
暴露给 `@tarojs/taro` 的 H5 端 API。
44

55
需要配合 `babel-plugin-transform-taroapi` 才能使用 ES6 default import 的语法,相关配置详情在 `babel-preset-taro` 中。
6+
7+
## H5 离屏画布类型
8+
9+
H5 项目通过 `@tarojs/taro` 调用离屏画布时,可在 H5 专用 tsconfig 的 `compilerOptions.types` 中加入 `@tarojs/taro-h5/types/h5`,或在 H5 专用声明文件中引用:
10+
11+
```ts
12+
/// <reference types="@tarojs/taro-h5/types/h5" />
13+
```
14+
15+
此入口为 `Taro.createOffscreenCanvas().getContext()` 提供可空的浏览器 2D/WebGL 类型。调用方应先判断上下文是否存在。小程序项目继续使用默认类型入口。
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import Taro from '@tarojs/taro'
2+
3+
import type {} from '../../types/h5'
4+
5+
export async function drawWithPublicApi (url: string) {
6+
const canvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
7+
const context = canvas.getContext('2d')
8+
// @ts-expect-error H5 contexts can be unavailable.
9+
context.clearRect(0, 0, 300, 150)
10+
if (!context) return
11+
const image = canvas.createImage()
12+
image.onload = null
13+
image.onerror = null
14+
await new Promise<void>((resolve, reject) => {
15+
image.onload = () => resolve()
16+
image.onerror = reject
17+
image.src = url
18+
})
19+
context.clearRect(0, 0, 300, 150)
20+
context.drawImage(image, 0, 0)
21+
return context.getImageData(0, 0, 300, 150)
22+
}
23+
const gl = Taro.createOffscreenCanvas({ type: 'webgl' }).getContext('webgl')
24+
if (gl) gl.clear(gl.COLOR_BUFFER_BIT)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { createOffscreenCanvas } from '@tarojs/taro-h5'
2+
3+
describe('createOffscreenCanvas', () => {
4+
const original = Object.getOwnPropertyDescriptor(globalThis, 'OffscreenCanvas')
5+
6+
afterEach(() => {
7+
if (original) Object.defineProperty(globalThis, 'OffscreenCanvas', original)
8+
else Reflect.deleteProperty(globalThis, 'OffscreenCanvas')
9+
jest.restoreAllMocks()
10+
})
11+
12+
it('keeps dimensions and context on the native canvas', () => {
13+
const context = {}
14+
const backing = { width: 0, height: 0, getContext: jest.fn().mockReturnValue(context) }
15+
const native = jest.fn().mockReturnValue(backing)
16+
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native })
17+
18+
const canvas = createOffscreenCanvas({ type: '2d', width: 20, height: 10 })
19+
expect(native).toHaveBeenCalledWith(20, 10)
20+
expect(canvas.height).toBe(10)
21+
canvas.width = 30
22+
expect(backing.width).toBe(30)
23+
expect(canvas.getContext('webgl')).toBeNull()
24+
expect(canvas.getContext('2d')).toBe(context)
25+
expect(backing.getContext).toHaveBeenCalledTimes(2)
26+
expect(canvas.createImage()).toBeInstanceOf(HTMLImageElement)
27+
})
28+
29+
it('falls back when the native canvas cannot provide the requested WebGL context', () => {
30+
const nativeContext = jest.fn().mockReturnValue(null)
31+
const native = jest.fn().mockImplementation(() => ({ getContext: nativeContext }))
32+
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: native })
33+
const context = { clear: jest.fn() }
34+
const htmlContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as unknown as WebGLRenderingContext)
35+
const canvas = createOffscreenCanvas({ type: 'webgl', width: 40, height: 30 })
36+
expect(nativeContext).toHaveBeenCalledWith('webgl')
37+
expect(canvas.getContext('webgl')).toBe(context)
38+
expect(canvas.getContext('2d')).toBeNull()
39+
expect([canvas.width, canvas.height]).toEqual([40, 30])
40+
expect((htmlContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false)
41+
})
42+
43+
it('falls back to a detached HTML canvas and defaults to WebGL', () => {
44+
Object.defineProperty(globalThis, 'OffscreenCanvas', { configurable: true, value: undefined })
45+
const getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null)
46+
const canvas = createOffscreenCanvas({})
47+
expect([canvas.width, canvas.height]).toEqual([300, 150])
48+
expect(canvas.getContext('webgl')).toBeNull()
49+
expect(getContext).toHaveBeenCalledWith('webgl')
50+
expect((getContext.mock.instances[0] as HTMLCanvasElement).isConnected).toBe(false)
51+
})
52+
})
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { resolve } from 'node:path'
2+
3+
import * as ts from 'typescript'
4+
5+
it.each(['offscreen.types.ts', 'offscreen.h5.types.ts'])('compiles %s under strict null checking', filename => {
6+
const fixture = resolve(__dirname, filename)
7+
const program = ts.createProgram([fixture], {
8+
noEmit: true,
9+
strictNullChecks: true,
10+
skipLibCheck: true,
11+
esModuleInterop: true,
12+
target: ts.ScriptTarget.ES2020,
13+
module: ts.ModuleKind.CommonJS,
14+
types: [],
15+
})
16+
const source = program.getSourceFile(fixture)!
17+
const diagnostics = [
18+
...program.getSyntacticDiagnostics(source),
19+
...program.getSemanticDiagnostics(source),
20+
]
21+
expect(diagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([])
22+
})
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import Taro from '@tarojs/taro'
2+
3+
import { createOffscreenCanvas } from '../../src/index'
4+
5+
declare function acceptContext(context: Taro.RenderingContext): void
6+
declare function acceptHandler(handler: (...args: any[]) => any): void
7+
declare const ordinaryCanvas: Taro.Canvas
8+
9+
const miniCanvas = Taro.createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
10+
acceptContext(miniCanvas.getContext('2d'))
11+
acceptHandler(miniCanvas.createImage().onload)
12+
acceptHandler(miniCanvas.createImage().onerror)
13+
acceptHandler(ordinaryCanvas.createImage().onload)
14+
acceptHandler(ordinaryCanvas.createImage().onerror)
15+
16+
export async function drawImage (url: string) {
17+
const canvas = createOffscreenCanvas({ type: '2d', width: 300, height: 150 })
18+
const context = canvas.getContext('2d')
19+
// @ts-expect-error H5 callers must check for an unavailable context.
20+
context.clearRect(0, 0, 300, 150)
21+
if (!context) throw new Error('2D context is unavailable')
22+
23+
const image = canvas.createImage()
24+
const initialOnload: typeof image.onload = null
25+
const initialOnerror: typeof image.onerror = null
26+
image.onload = initialOnload
27+
image.onerror = initialOnerror
28+
await new Promise<void>((resolve, reject) => {
29+
image.onload = () => resolve()
30+
image.onerror = reject
31+
image.src = url
32+
})
33+
context.clearRect(0, 0, 300, 150)
34+
context.drawImage(image, 0, 0)
35+
return context.getImageData(0, 0, 300, 150)
36+
}
37+
38+
const gl = createOffscreenCanvas({ type: 'webgl' }).getContext('webgl')
39+
if (gl) gl.clear(gl.COLOR_BUFFER_BIT)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import Taro from '@tarojs/api'
2+
3+
import { loadHarmonyApi } from '../helpers/loadHarmonyApi'
4+
5+
afterEach(() => jest.restoreAllMocks())
6+
7+
it('keeps the Harmony Hybrid createOffscreenCanvas placeholder at the public entry', async () => {
8+
jest.replaceProperty(process.env, 'NODE_ENV', 'production')
9+
jest.spyOn(console, 'warn').mockImplementation(() => {})
10+
const createElement = jest.spyOn(document, 'createElement')
11+
const unsupported = jest.fn()
12+
const createOffscreenCanvas = await loadHarmonyApi('createOffscreenCanvas')
13+
const options = { type: '2d' as const, width: 20, height: 10 }
14+
15+
Taro.eventCenter.on('__taroNotSupport', unsupported)
16+
try {
17+
await expect(createOffscreenCanvas(options)).resolves.toEqual({ errMsg: '暂时不支持 API' })
18+
expect(unsupported).toHaveBeenCalledWith({
19+
name: 'createOffscreenCanvas', args: [options], type: 'method', category: 'temporarily',
20+
})
21+
expect(createElement).not.toHaveBeenCalled()
22+
} finally {
23+
Taro.eventCenter.off('__taroNotSupport', unsupported)
24+
}
25+
})
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { existsSync } from 'node:fs'
2+
import { isAbsolute, resolve } from 'node:path'
3+
import { runInNewContext } from 'node:vm'
4+
5+
import { rollup } from 'rollup'
6+
7+
import type Taro from '@tarojs/api'
8+
9+
/** Import a named API from the generated public entry through a real Rollup consumer. */
10+
export async function loadHarmonyApi<K extends keyof typeof Taro> (name: K): Promise<(typeof Taro)[K]> {
11+
const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js')
12+
if (!existsSync(publicApi)) {
13+
throw new Error('Build Harmony Hybrid first, or run pnpm --filter @tarojs/taro-h5 test:integration')
14+
}
15+
const consumer = '\0harmony-api-consumer'
16+
const bundle = await rollup({
17+
input: consumer,
18+
external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id),
19+
treeshake: { moduleSideEffects: false },
20+
plugins: [{
21+
name: 'harmony-api-consumer',
22+
resolveId: id => id === consumer ? id : null,
23+
load: id => id === consumer ? `export { ${String(name)} } from ${JSON.stringify(publicApi)}` : null,
24+
}],
25+
})
26+
const exports: Pick<typeof Taro, K> = Object.create(null)
27+
try {
28+
const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' })
29+
runInNewContext(output[0].code, { exports, require, process, console, document, window })
30+
return exports[name]
31+
} finally {
32+
await bundle.close()
33+
}
34+
}

‎packages/taro-h5/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"rollup": "rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript --bundleConfigAsCjs",
2727
"test": "jest",
2828
"test:ci": "jest --ci -i --coverage --silent",
29+
"test:integration": "pnpm run build && pnpm --filter @tarojs/plugin-platform-harmony-hybrid run build && jest --ci -i --testMatch \"**/integration/**/*.test.ts\"",
2930
"test:dev": "jest --watch",
3031
"test:coverage": "jest --coverage"
3132
},

0 commit comments

Comments
 (0)