@hozo/canvas 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +57 -0
- package/dist/hit-test.d.ts +3 -3
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +43 -4
- package/dist/hit-test.js.map +1 -1
- package/dist/index.d.ts +19 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +85 -10
- package/dist/index.js.map +1 -1
- package/dist/index.native.d.ts +19 -9
- package/dist/index.native.d.ts.map +1 -1
- package/dist/index.native.js +106 -13
- package/dist/index.native.js.map +1 -1
- package/dist/render-canvas-2d.d.ts +3 -2
- package/dist/render-canvas-2d.d.ts.map +1 -1
- package/dist/render-canvas-2d.js +280 -6
- package/dist/render-canvas-2d.js.map +1 -1
- package/dist/scene.d.ts +110 -8
- package/dist/scene.d.ts.map +1 -1
- package/dist/scene.js +148 -7
- package/dist/scene.js.map +1 -1
- package/package.json +3 -2
- package/src/hit-test.ts +48 -3
- package/src/index.native.tsx +198 -25
- package/src/index.tsx +91 -8
- package/src/render-canvas-2d.ts +374 -4
- package/src/scene.tsx +238 -4
package/src/index.tsx
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
type CSSProperties,
|
|
4
4
|
type ReactNode,
|
|
5
5
|
type PointerEvent as ReactPointerEvent,
|
|
6
|
+
useCallback,
|
|
6
7
|
useEffect,
|
|
7
8
|
useLayoutEffect,
|
|
8
9
|
useMemo,
|
|
@@ -20,10 +21,13 @@ import {
|
|
|
20
21
|
import { renderCanvas2D } from './render-canvas-2d.ts'
|
|
21
22
|
import {
|
|
22
23
|
BoundedCache,
|
|
24
|
+
type CanvasScene,
|
|
23
25
|
Circle,
|
|
24
26
|
Clip,
|
|
25
27
|
canvasControls,
|
|
28
|
+
canvasMeshTextureColor,
|
|
26
29
|
canvasPressEvent,
|
|
30
|
+
canvasTextureUri,
|
|
27
31
|
canvasUnreadableText,
|
|
28
32
|
cssFontShorthand,
|
|
29
33
|
Ellipse,
|
|
@@ -35,6 +39,7 @@ import {
|
|
|
35
39
|
reportUnreadableText,
|
|
36
40
|
Text,
|
|
37
41
|
type TextProps,
|
|
42
|
+
TriangleMesh,
|
|
38
43
|
useCanvasScene,
|
|
39
44
|
} from './scene.tsx'
|
|
40
45
|
import { wrapText } from './wrap-text.ts'
|
|
@@ -54,10 +59,13 @@ export { type CanvasViewport, renderCanvas2D } from './render-canvas-2d.ts'
|
|
|
54
59
|
export type {
|
|
55
60
|
CanvasDestination,
|
|
56
61
|
CanvasInteractionProps,
|
|
62
|
+
CanvasMeshTexture,
|
|
57
63
|
CanvasPaintProps,
|
|
58
64
|
CanvasPressEvent,
|
|
59
65
|
CanvasScene,
|
|
60
66
|
CanvasSceneNode,
|
|
67
|
+
CanvasTextureSource,
|
|
68
|
+
CanvasTextureWrap,
|
|
61
69
|
CanvasTransform,
|
|
62
70
|
CircleProps,
|
|
63
71
|
ClipProps,
|
|
@@ -67,6 +75,7 @@ export type {
|
|
|
67
75
|
PathProps,
|
|
68
76
|
RectProps,
|
|
69
77
|
RoundedRectProps,
|
|
78
|
+
TriangleMeshProps,
|
|
70
79
|
} from './scene.tsx'
|
|
71
80
|
export { CanvasSceneStore } from './scene.tsx'
|
|
72
81
|
// The rule on its own, for a caller with a measurement of its own --
|
|
@@ -150,6 +159,7 @@ export function wrapCanvasText(props: TextProps, maxWidth: number): string[] | u
|
|
|
150
159
|
export type CanvasProps = CanvasAccessibilityProps & {
|
|
151
160
|
children?: ReactNode
|
|
152
161
|
className?: string
|
|
162
|
+
onSizeChange?: (size: CanvasSize) => void
|
|
153
163
|
style?: CSSProperties
|
|
154
164
|
width?: number
|
|
155
165
|
height?: number
|
|
@@ -158,7 +168,7 @@ export type CanvasProps = CanvasAccessibilityProps & {
|
|
|
158
168
|
testID?: string
|
|
159
169
|
}
|
|
160
170
|
|
|
161
|
-
interface
|
|
171
|
+
export interface CanvasSize {
|
|
162
172
|
width: number
|
|
163
173
|
height: number
|
|
164
174
|
pixelRatio: number
|
|
@@ -177,6 +187,7 @@ function Root({
|
|
|
177
187
|
decorative,
|
|
178
188
|
accessibilityLabel,
|
|
179
189
|
accessibleFallback,
|
|
190
|
+
onSizeChange,
|
|
180
191
|
testID,
|
|
181
192
|
}: CanvasProps) {
|
|
182
193
|
const canvasRef = useRef<HTMLCanvasElement>(null)
|
|
@@ -184,11 +195,68 @@ function Root({
|
|
|
184
195
|
const navigation = useHozoNavigation()
|
|
185
196
|
const { scene, collector, isInteractive, press, activate, interactions, interactionRevision } =
|
|
186
197
|
useCanvasScene(children)
|
|
187
|
-
const [size, setSize] = useState<
|
|
198
|
+
const [size, setSize] = useState<CanvasSize>(() => ({
|
|
188
199
|
width: width ?? viewBox?.[2] ?? 300,
|
|
189
200
|
height: height ?? viewBox?.[3] ?? 150,
|
|
190
201
|
pixelRatio: 1,
|
|
191
202
|
}))
|
|
203
|
+
const sizeCallback = useRef(onSizeChange)
|
|
204
|
+
sizeCallback.current = onSizeChange
|
|
205
|
+
const textureImages = useRef(new Map<string, HTMLImageElement>())
|
|
206
|
+
const textureMounted = useRef(false)
|
|
207
|
+
const [textureRevision, setTextureRevision] = useState(0)
|
|
208
|
+
|
|
209
|
+
useEffect(() => {
|
|
210
|
+
textureMounted.current = true
|
|
211
|
+
return () => {
|
|
212
|
+
textureMounted.current = false
|
|
213
|
+
}
|
|
214
|
+
}, [])
|
|
215
|
+
|
|
216
|
+
useEffect(() => {
|
|
217
|
+
if (typeof Image === 'undefined') return
|
|
218
|
+
const visit = (nodes: CanvasScene) => {
|
|
219
|
+
for (const node of nodes) {
|
|
220
|
+
if (node.kind === 'triangle-mesh' && node.props.texture) {
|
|
221
|
+
const uri = canvasTextureUri(node.props.texture.source)
|
|
222
|
+
if (!uri) continue
|
|
223
|
+
const color = canvasMeshTextureColor(node.props.texture)
|
|
224
|
+
const readable = color && (color.r !== 1 || color.g !== 1 || color.b !== 1)
|
|
225
|
+
const cached = textureImages.current.get(uri)
|
|
226
|
+
if (cached && (!readable || cached.crossOrigin === 'anonymous')) continue
|
|
227
|
+
const image = new Image()
|
|
228
|
+
// Static RGB modulation reads pixels once. Request CORS only for
|
|
229
|
+
// that path; ordinary images must still draw without CORS support.
|
|
230
|
+
if (readable) image.crossOrigin = 'anonymous'
|
|
231
|
+
textureImages.current.set(uri, image)
|
|
232
|
+
image.onload = () => {
|
|
233
|
+
if (textureImages.current.get(uri) !== image) return
|
|
234
|
+
if (textureMounted.current) setTextureRevision((revision) => revision + 1)
|
|
235
|
+
}
|
|
236
|
+
image.onerror = () => {
|
|
237
|
+
if (textureImages.current.get(uri) !== image) return
|
|
238
|
+
textureImages.current.delete(uri)
|
|
239
|
+
if (readable)
|
|
240
|
+
console.warn(
|
|
241
|
+
'[hozo] Portable texture colour modulation could not load a readable image; external images need CORS support.',
|
|
242
|
+
)
|
|
243
|
+
if (textureMounted.current) setTextureRevision((revision) => revision + 1)
|
|
244
|
+
}
|
|
245
|
+
image.src = uri
|
|
246
|
+
} else if (node.kind === 'group' || node.kind === 'clip') {
|
|
247
|
+
visit(node.children)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
visit(scene)
|
|
252
|
+
}, [scene])
|
|
253
|
+
|
|
254
|
+
const textureImage = useCallback((source: Parameters<typeof canvasTextureUri>[0]) => {
|
|
255
|
+
const uri = canvasTextureUri(source)
|
|
256
|
+
if (!uri) return undefined
|
|
257
|
+
const image = textureImages.current.get(uri)
|
|
258
|
+
return image?.complete && image.naturalWidth > 0 ? image : undefined
|
|
259
|
+
}, [])
|
|
192
260
|
|
|
193
261
|
useIsoLayoutEffect(() => {
|
|
194
262
|
const canvas = canvasRef.current
|
|
@@ -209,19 +277,33 @@ function Root({
|
|
|
209
277
|
)
|
|
210
278
|
}
|
|
211
279
|
measure()
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
280
|
+
const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure)
|
|
281
|
+
observer?.observe(canvas)
|
|
282
|
+
const browserWindow = globalThis.window
|
|
283
|
+
if (typeof browserWindow?.addEventListener === 'function') {
|
|
284
|
+
browserWindow.addEventListener('resize', measure)
|
|
285
|
+
}
|
|
286
|
+
return () => {
|
|
287
|
+
observer?.disconnect()
|
|
288
|
+
if (typeof browserWindow?.removeEventListener === 'function') {
|
|
289
|
+
browserWindow.removeEventListener('resize', measure)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
216
292
|
}, [width, height, viewBox])
|
|
217
293
|
|
|
294
|
+
useIsoLayoutEffect(() => {
|
|
295
|
+
sizeCallback.current?.(size)
|
|
296
|
+
}, [size])
|
|
297
|
+
|
|
218
298
|
useIsoLayoutEffect(() => {
|
|
219
299
|
const context = canvasRef.current?.getContext('2d')
|
|
220
300
|
if (!context) return
|
|
221
|
-
renderCanvas2D(context, scene, { ...size, viewBox, fit })
|
|
222
|
-
}, [scene, size, viewBox, fit])
|
|
301
|
+
renderCanvas2D(context, scene, { ...size, viewBox, fit }, textureImage)
|
|
302
|
+
}, [scene, size, viewBox, fit, textureImage, textureRevision])
|
|
223
303
|
|
|
224
304
|
const rootStyle: CSSProperties = {
|
|
305
|
+
width: width ?? style?.width ?? 300,
|
|
306
|
+
height: height ?? style?.height ?? 150,
|
|
225
307
|
...style,
|
|
226
308
|
...(width === undefined ? null : { width }),
|
|
227
309
|
...(height === undefined ? null : { height }),
|
|
@@ -507,4 +589,5 @@ export const Canvas = Object.assign(Root, {
|
|
|
507
589
|
Line,
|
|
508
590
|
|
|
509
591
|
Path,
|
|
592
|
+
TriangleMesh,
|
|
510
593
|
})
|
package/src/render-canvas-2d.ts
CHANGED
|
@@ -3,12 +3,20 @@ import {
|
|
|
3
3
|
type CanvasPaintProps,
|
|
4
4
|
type CanvasScene,
|
|
5
5
|
type CanvasSceneNode,
|
|
6
|
+
type CanvasTextureSource,
|
|
7
|
+
type CanvasTextureWrap,
|
|
6
8
|
type CanvasTransform,
|
|
7
9
|
type ClipProps,
|
|
10
|
+
canvasMeshTextureColor,
|
|
11
|
+
canvasMeshTextureWrap,
|
|
8
12
|
cssFontShorthand,
|
|
9
13
|
isGradient,
|
|
10
14
|
paintFills,
|
|
11
15
|
paintStrokes,
|
|
16
|
+
triangleMeshColor,
|
|
17
|
+
triangleMeshColorCss,
|
|
18
|
+
triangleMeshIndices,
|
|
19
|
+
triangleMeshTextureCoordinate,
|
|
12
20
|
unhandledShape,
|
|
13
21
|
} from './scene.tsx'
|
|
14
22
|
import type { CanvasViewport } from './viewport.ts'
|
|
@@ -16,6 +24,135 @@ import { textLines } from './wrap-text.ts'
|
|
|
16
24
|
|
|
17
25
|
export type { CanvasViewport } from './viewport.ts'
|
|
18
26
|
|
|
27
|
+
type CanvasTextureImage = (source: CanvasTextureSource) => CanvasImageSource | undefined
|
|
28
|
+
|
|
29
|
+
const modulatedTextures = new WeakMap<object, Map<string, CanvasImageSource>>()
|
|
30
|
+
const unreadableTextures = new WeakSet<object>()
|
|
31
|
+
const mirroredTextures = new WeakMap<object, Map<string, CanvasImageSource>>()
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Canvas patterns only repeat. Build a two-tile period on each mirrored axis
|
|
35
|
+
* once per decoded image, then repeat that period without folding triangle UVs.
|
|
36
|
+
* Folding vertices alone would interpolate through the wrong side of a seam.
|
|
37
|
+
*/
|
|
38
|
+
function mirroredTexture(
|
|
39
|
+
image: CanvasImageSource,
|
|
40
|
+
wrapX: CanvasTextureWrap,
|
|
41
|
+
wrapY: CanvasTextureWrap,
|
|
42
|
+
): CanvasImageSource | undefined {
|
|
43
|
+
const mirrorX = wrapX === 'mirror'
|
|
44
|
+
const mirrorY = wrapY === 'mirror'
|
|
45
|
+
if (!mirrorX && !mirrorY) return image
|
|
46
|
+
const key = `${mirrorX}/${mirrorY}`
|
|
47
|
+
const cached = mirroredTextures.get(image)?.get(key)
|
|
48
|
+
if (cached) return cached
|
|
49
|
+
const dimensions = imageDimensions(image)
|
|
50
|
+
if (!dimensions) return undefined
|
|
51
|
+
const columns = mirrorX ? 2 : 1
|
|
52
|
+
const rows = mirrorY ? 2 : 1
|
|
53
|
+
const width = dimensions.width * columns
|
|
54
|
+
const height = dimensions.height * rows
|
|
55
|
+
const surface =
|
|
56
|
+
typeof OffscreenCanvas === 'function'
|
|
57
|
+
? new OffscreenCanvas(width, height)
|
|
58
|
+
: typeof document === 'undefined'
|
|
59
|
+
? undefined
|
|
60
|
+
: Object.assign(document.createElement('canvas'), { width, height })
|
|
61
|
+
const context = surface?.getContext('2d')
|
|
62
|
+
if (!surface || !context) return undefined
|
|
63
|
+
for (let y = 0; y < rows; y += 1) {
|
|
64
|
+
for (let x = 0; x < columns; x += 1) {
|
|
65
|
+
context.save()
|
|
66
|
+
context.translate(x === 1 ? width : 0, y === 1 ? height : 0)
|
|
67
|
+
context.scale(x === 1 ? -1 : 1, y === 1 ? -1 : 1)
|
|
68
|
+
context.drawImage(image, 0, 0, dimensions.width, dimensions.height)
|
|
69
|
+
context.restore()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
// At most three variants (X, Y, XY) belong to an image; the WeakMap does not
|
|
73
|
+
// retain the decoded source after the scene/image cache releases it.
|
|
74
|
+
const variants = mirroredTextures.get(image) ?? new Map<string, CanvasImageSource>()
|
|
75
|
+
variants.set(key, surface)
|
|
76
|
+
mirroredTextures.set(image, variants)
|
|
77
|
+
return surface
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function srgbToLinear(channel: number): number {
|
|
81
|
+
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function linearToSrgb(channel: number): number {
|
|
85
|
+
return channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Canvas brightness/compositing operates on encoded channels rather than the
|
|
90
|
+
* linear RGB Three.js multiplies. Pay this cost once per image/colour, not per
|
|
91
|
+
* triangle/frame, and keep the subsequent affine draw path host-backed.
|
|
92
|
+
*/
|
|
93
|
+
function softwareModulatedTexture(
|
|
94
|
+
image: CanvasImageSource,
|
|
95
|
+
color: { r: number; g: number; b: number },
|
|
96
|
+
): CanvasImageSource | undefined {
|
|
97
|
+
const dimensions = imageDimensions(image)
|
|
98
|
+
if (!dimensions) return undefined
|
|
99
|
+
const key = image as object
|
|
100
|
+
if (unreadableTextures.has(key)) return undefined
|
|
101
|
+
const cacheKey = `${color.r}/${color.g}/${color.b}`
|
|
102
|
+
const variants = modulatedTextures.get(key)
|
|
103
|
+
const cached = variants?.get(cacheKey)
|
|
104
|
+
if (cached) return cached
|
|
105
|
+
const surface =
|
|
106
|
+
typeof OffscreenCanvas === 'function'
|
|
107
|
+
? new OffscreenCanvas(dimensions.width, dimensions.height)
|
|
108
|
+
: typeof document === 'undefined'
|
|
109
|
+
? undefined
|
|
110
|
+
: Object.assign(document.createElement('canvas'), dimensions)
|
|
111
|
+
if (!surface) return undefined
|
|
112
|
+
const context = surface.getContext('2d', { willReadFrequently: true })
|
|
113
|
+
if (!context) return undefined
|
|
114
|
+
try {
|
|
115
|
+
context.drawImage(image, 0, 0, dimensions.width, dimensions.height)
|
|
116
|
+
const pixels = context.getImageData(0, 0, dimensions.width, dimensions.height)
|
|
117
|
+
const multipliers = [color.r, color.g, color.b]
|
|
118
|
+
// Only 256 encoded input values exist. Avoid millions of pow() calls when
|
|
119
|
+
// a large static texture is tinted for the first time.
|
|
120
|
+
const tables = multipliers.map((multiplier) =>
|
|
121
|
+
Uint8ClampedArray.from({ length: 256 }, (_, value) =>
|
|
122
|
+
Math.round(
|
|
123
|
+
Math.max(0, Math.min(1, linearToSrgb(srgbToLinear(value / 255) * multiplier))) * 255,
|
|
124
|
+
),
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
for (let offset = 0; offset < pixels.data.length; offset += 4) {
|
|
128
|
+
for (let channel = 0; channel < 3; channel += 1) {
|
|
129
|
+
pixels.data[offset + channel] = tables[channel]![pixels.data[offset + channel] ?? 0]!
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
context.putImageData(pixels, 0, 0)
|
|
133
|
+
} catch {
|
|
134
|
+
// A cross-origin image without CORS can be drawn but not read back. Report
|
|
135
|
+
// the limitation once rather than quietly substituting an untinted image.
|
|
136
|
+
if (!unreadableTextures.has(key)) {
|
|
137
|
+
unreadableTextures.add(key)
|
|
138
|
+
console.warn(
|
|
139
|
+
'[hozo] Portable texture colour modulation requires a readable image (same-origin or CORS-enabled).',
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
return undefined
|
|
143
|
+
}
|
|
144
|
+
const byColor = variants ?? new Map<string, CanvasImageSource>()
|
|
145
|
+
// Animated colours must not retain an unbounded collection of pixel copies.
|
|
146
|
+
const limit = Math.max(
|
|
147
|
+
1,
|
|
148
|
+
Math.min(8, Math.floor((16 * 1024 * 1024) / (dimensions.width * dimensions.height * 4))),
|
|
149
|
+
)
|
|
150
|
+
if (byColor.size >= limit) byColor.delete(byColor.keys().next().value!)
|
|
151
|
+
byColor.set(cacheKey, surface)
|
|
152
|
+
modulatedTextures.set(key, byColor)
|
|
153
|
+
return surface
|
|
154
|
+
}
|
|
155
|
+
|
|
19
156
|
function applyTransform(context: CanvasRenderingContext2D, transform?: CanvasTransform) {
|
|
20
157
|
if (!transform) return
|
|
21
158
|
const originX = transform.originX ?? 0
|
|
@@ -91,18 +228,195 @@ function pathForClip(context: CanvasRenderingContext2D, props: Omit<ClipProps, '
|
|
|
91
228
|
context.clip()
|
|
92
229
|
}
|
|
93
230
|
|
|
94
|
-
function
|
|
231
|
+
function trianglePath(
|
|
232
|
+
context: CanvasRenderingContext2D,
|
|
233
|
+
a: { x: number; y: number },
|
|
234
|
+
b: { x: number; y: number },
|
|
235
|
+
c: { x: number; y: number },
|
|
236
|
+
) {
|
|
237
|
+
context.beginPath()
|
|
238
|
+
context.moveTo(a.x, a.y)
|
|
239
|
+
context.lineTo(b.x, b.y)
|
|
240
|
+
context.lineTo(c.x, c.y)
|
|
241
|
+
context.closePath()
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The linear ramp whose alpha is one barycentric coordinate.
|
|
246
|
+
*
|
|
247
|
+
* That coordinate is zero on the edge opposite `vertex`, one at the
|
|
248
|
+
* vertex, and linear between them. Three such premultiplied contributions
|
|
249
|
+
* add to the same Gouraud colour Skia's Vertices computes. This is four
|
|
250
|
+
* bounded fills per face (one clear plus three contributions), not an
|
|
251
|
+
* accuracy-dependent tessellation that can explode with colour contrast.
|
|
252
|
+
*/
|
|
253
|
+
function vertexContribution(
|
|
254
|
+
context: CanvasRenderingContext2D,
|
|
255
|
+
vertex: { x: number; y: number },
|
|
256
|
+
edgeA: { x: number; y: number },
|
|
257
|
+
edgeB: { x: number; y: number },
|
|
258
|
+
color: { r: number; g: number; b: number; a?: number },
|
|
259
|
+
) {
|
|
260
|
+
const edgeX = edgeB.x - edgeA.x
|
|
261
|
+
const edgeY = edgeB.y - edgeA.y
|
|
262
|
+
const edgeLengthSquared = edgeX * edgeX + edgeY * edgeY
|
|
263
|
+
const alongEdge =
|
|
264
|
+
((vertex.x - edgeA.x) * edgeX + (vertex.y - edgeA.y) * edgeY) / edgeLengthSquared
|
|
265
|
+
const footX = edgeA.x + alongEdge * edgeX
|
|
266
|
+
const footY = edgeA.y + alongEdge * edgeY
|
|
267
|
+
const gradient = context.createLinearGradient(footX, footY, vertex.x, vertex.y)
|
|
268
|
+
// Keep the RGB endpoints equal. Whichever interpolation space the host
|
|
269
|
+
// uses, alpha alone becomes the barycentric weight; transparent black
|
|
270
|
+
// would darken on implementations that interpolate unpremultiplied RGB.
|
|
271
|
+
gradient.addColorStop(0, triangleMeshColorCss(color, 0))
|
|
272
|
+
gradient.addColorStop(1, triangleMeshColorCss(color))
|
|
273
|
+
return gradient
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function fillColoredTriangle(
|
|
277
|
+
context: CanvasRenderingContext2D,
|
|
278
|
+
a: { x: number; y: number },
|
|
279
|
+
b: { x: number; y: number },
|
|
280
|
+
c: { x: number; y: number },
|
|
281
|
+
colors: readonly [
|
|
282
|
+
{ r: number; g: number; b: number; a?: number },
|
|
283
|
+
{ r: number; g: number; b: number; a?: number },
|
|
284
|
+
{ r: number; g: number; b: number; a?: number },
|
|
285
|
+
],
|
|
286
|
+
) {
|
|
287
|
+
if ((b.x - a.x) * (c.y - a.y) === (b.y - a.y) * (c.x - a.x)) return
|
|
288
|
+
const left = Math.min(a.x, b.x, c.x)
|
|
289
|
+
const top = Math.min(a.y, b.y, c.y)
|
|
290
|
+
const width = Math.max(a.x, b.x, c.x) - left
|
|
291
|
+
const height = Math.max(a.y, b.y, c.y) - top
|
|
292
|
+
if (width === 0 || height === 0) return
|
|
293
|
+
|
|
294
|
+
context.save()
|
|
295
|
+
trianglePath(context, a, b, c)
|
|
296
|
+
context.clip()
|
|
297
|
+
context.globalCompositeOperation = 'destination-out'
|
|
298
|
+
context.fillStyle = 'black'
|
|
299
|
+
context.fillRect(left, top, width, height)
|
|
300
|
+
context.globalCompositeOperation = 'lighter'
|
|
301
|
+
const contributions = [
|
|
302
|
+
vertexContribution(context, a, b, c, colors[0]),
|
|
303
|
+
vertexContribution(context, b, c, a, colors[1]),
|
|
304
|
+
vertexContribution(context, c, a, b, colors[2]),
|
|
305
|
+
]
|
|
306
|
+
for (const contribution of contributions) {
|
|
307
|
+
context.fillStyle = contribution
|
|
308
|
+
context.fillRect(left, top, width, height)
|
|
309
|
+
}
|
|
310
|
+
context.restore()
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function imageDimensions(image: CanvasImageSource): { width: number; height: number } | undefined {
|
|
314
|
+
const value = image as unknown as {
|
|
315
|
+
naturalHeight?: number
|
|
316
|
+
naturalWidth?: number
|
|
317
|
+
videoHeight?: number
|
|
318
|
+
videoWidth?: number
|
|
319
|
+
height?: number
|
|
320
|
+
width?: number
|
|
321
|
+
}
|
|
322
|
+
const width = value.naturalWidth || value.videoWidth || value.width
|
|
323
|
+
const height = value.naturalHeight || value.videoHeight || value.height
|
|
324
|
+
return width && height && width > 0 && height > 0 ? { width, height } : undefined
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function fillTexturedTriangle(
|
|
328
|
+
context: CanvasRenderingContext2D,
|
|
329
|
+
vertices: readonly [{ x: number; y: number }, { x: number; y: number }, { x: number; y: number }],
|
|
330
|
+
coordinates: readonly [
|
|
331
|
+
{ x: number; y: number },
|
|
332
|
+
{ x: number; y: number },
|
|
333
|
+
{ x: number; y: number },
|
|
334
|
+
],
|
|
335
|
+
image: CanvasImageSource,
|
|
336
|
+
filter: 'linear' | 'nearest',
|
|
337
|
+
wrapX: CanvasTextureWrap,
|
|
338
|
+
wrapY: CanvasTextureWrap,
|
|
339
|
+
color: { r: number; g: number; b: number },
|
|
340
|
+
) {
|
|
341
|
+
const drawable =
|
|
342
|
+
color.r === 1 && color.g === 1 && color.b === 1 ? image : softwareModulatedTexture(image, color)
|
|
343
|
+
if (!drawable) return
|
|
344
|
+
const dimensions = imageDimensions(drawable)
|
|
345
|
+
if (!dimensions) return
|
|
346
|
+
const [a, b, c] = vertices
|
|
347
|
+
const [ta, tb, tc] = coordinates.map(({ x, y }) => ({
|
|
348
|
+
x: x * dimensions.width,
|
|
349
|
+
y: y * dimensions.height,
|
|
350
|
+
})) as [{ x: number; y: number }, { x: number; y: number }, { x: number; y: number }]
|
|
351
|
+
const denominator = ta.x * (tb.y - tc.y) + tb.x * (tc.y - ta.y) + tc.x * (ta.y - tb.y)
|
|
352
|
+
if (denominator === 0) return
|
|
353
|
+
const x = [a.x, b.x, c.x]
|
|
354
|
+
const y = [a.y, b.y, c.y]
|
|
355
|
+
const u = [ta.x, tb.x, tc.x]
|
|
356
|
+
const v = [ta.y, tb.y, tc.y]
|
|
357
|
+
const affine = (values: number[]) => ({
|
|
358
|
+
first:
|
|
359
|
+
((values[0] ?? 0) * (v[1]! - v[2]!) +
|
|
360
|
+
(values[1] ?? 0) * (v[2]! - v[0]!) +
|
|
361
|
+
(values[2] ?? 0) * (v[0]! - v[1]!)) /
|
|
362
|
+
denominator,
|
|
363
|
+
second:
|
|
364
|
+
((values[0] ?? 0) * (u[2]! - u[1]!) +
|
|
365
|
+
(values[1] ?? 0) * (u[0]! - u[2]!) +
|
|
366
|
+
(values[2] ?? 0) * (u[1]! - u[0]!)) /
|
|
367
|
+
denominator,
|
|
368
|
+
offset:
|
|
369
|
+
((values[0] ?? 0) * (u[1]! * v[2]! - u[2]! * v[1]!) +
|
|
370
|
+
(values[1] ?? 0) * (u[2]! * v[0]! - u[0]! * v[2]!) +
|
|
371
|
+
(values[2] ?? 0) * (u[0]! * v[1]! - u[1]! * v[0]!)) /
|
|
372
|
+
denominator,
|
|
373
|
+
})
|
|
374
|
+
const horizontal = affine(x)
|
|
375
|
+
const vertical = affine(y)
|
|
376
|
+
|
|
377
|
+
context.save()
|
|
378
|
+
trianglePath(context, a, b, c)
|
|
379
|
+
context.clip()
|
|
380
|
+
context.imageSmoothingEnabled = filter === 'linear'
|
|
381
|
+
context.transform(
|
|
382
|
+
horizontal.first,
|
|
383
|
+
vertical.first,
|
|
384
|
+
horizontal.second,
|
|
385
|
+
vertical.second,
|
|
386
|
+
horizontal.offset,
|
|
387
|
+
vertical.offset,
|
|
388
|
+
)
|
|
389
|
+
if (wrapX !== 'clamp' || wrapY !== 'clamp') {
|
|
390
|
+
const repetition = wrapX !== 'clamp' ? (wrapY !== 'clamp' ? 'repeat' : 'repeat-x') : 'repeat-y'
|
|
391
|
+
const tile = mirroredTexture(drawable, wrapX, wrapY)
|
|
392
|
+
const pattern = tile ? context.createPattern(tile, repetition) : null
|
|
393
|
+
if (pattern) {
|
|
394
|
+
context.fillStyle = pattern
|
|
395
|
+
trianglePath(context, ta, tb, tc)
|
|
396
|
+
context.fill()
|
|
397
|
+
}
|
|
398
|
+
} else {
|
|
399
|
+
context.drawImage(drawable, 0, 0, dimensions.width, dimensions.height)
|
|
400
|
+
}
|
|
401
|
+
context.restore()
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function drawNode(
|
|
405
|
+
context: CanvasRenderingContext2D,
|
|
406
|
+
node: CanvasSceneNode,
|
|
407
|
+
textureImage?: CanvasTextureImage,
|
|
408
|
+
) {
|
|
95
409
|
context.save()
|
|
96
410
|
try {
|
|
97
411
|
switch (node.kind) {
|
|
98
412
|
case 'group':
|
|
99
413
|
context.globalAlpha *= node.props.opacity ?? 1
|
|
100
414
|
applyTransform(context, node.props.transform)
|
|
101
|
-
for (const child of node.children) drawNode(context, child)
|
|
415
|
+
for (const child of node.children) drawNode(context, child, textureImage)
|
|
102
416
|
return
|
|
103
417
|
case 'clip':
|
|
104
418
|
pathForClip(context, node.props)
|
|
105
|
-
for (const child of node.children) drawNode(context, child)
|
|
419
|
+
for (const child of node.children) drawNode(context, child, textureImage)
|
|
106
420
|
return
|
|
107
421
|
case 'rect': {
|
|
108
422
|
applyPaint(context, node.props)
|
|
@@ -213,6 +527,61 @@ function drawNode(context: CanvasRenderingContext2D, node: CanvasSceneNode) {
|
|
|
213
527
|
if (hasStroke) context.stroke(path)
|
|
214
528
|
return
|
|
215
529
|
}
|
|
530
|
+
case 'triangle-mesh': {
|
|
531
|
+
const indices = triangleMeshIndices(node.props)
|
|
532
|
+
if (indices.length === 0 || node.props.fill === 'none') return
|
|
533
|
+
applyPaint(context, node.props)
|
|
534
|
+
const texture = node.props.texture
|
|
535
|
+
const image = texture ? textureImage?.(texture.source) : undefined
|
|
536
|
+
if (texture && !image) return
|
|
537
|
+
for (let offset = 0; offset < indices.length; offset += 3) {
|
|
538
|
+
const a = node.props.vertices[indices[offset] as number]
|
|
539
|
+
const b = node.props.vertices[indices[offset + 1] as number]
|
|
540
|
+
const c = node.props.vertices[indices[offset + 2] as number]
|
|
541
|
+
if (!a || !b || !c) continue
|
|
542
|
+
if (texture && image) {
|
|
543
|
+
const [wrapX, wrapY] = canvasMeshTextureWrap(texture)
|
|
544
|
+
const color = canvasMeshTextureColor(texture)
|
|
545
|
+
if (color === undefined) continue
|
|
546
|
+
const textureA = triangleMeshTextureCoordinate(
|
|
547
|
+
texture.coordinates[indices[offset] as number],
|
|
548
|
+
wrapX,
|
|
549
|
+
wrapY,
|
|
550
|
+
)
|
|
551
|
+
const textureB = triangleMeshTextureCoordinate(
|
|
552
|
+
texture.coordinates[indices[offset + 1] as number],
|
|
553
|
+
wrapX,
|
|
554
|
+
wrapY,
|
|
555
|
+
)
|
|
556
|
+
const textureC = triangleMeshTextureCoordinate(
|
|
557
|
+
texture.coordinates[indices[offset + 2] as number],
|
|
558
|
+
wrapX,
|
|
559
|
+
wrapY,
|
|
560
|
+
)
|
|
561
|
+
if (!textureA || !textureB || !textureC) continue
|
|
562
|
+
fillTexturedTriangle(
|
|
563
|
+
context,
|
|
564
|
+
[a, b, c],
|
|
565
|
+
[textureA, textureB, textureC],
|
|
566
|
+
image,
|
|
567
|
+
texture.filter ?? 'linear',
|
|
568
|
+
wrapX,
|
|
569
|
+
wrapY,
|
|
570
|
+
color,
|
|
571
|
+
)
|
|
572
|
+
} else if (node.props.colors) {
|
|
573
|
+
const colorA = triangleMeshColor(node.props.colors[indices[offset] as number])
|
|
574
|
+
const colorB = triangleMeshColor(node.props.colors[indices[offset + 1] as number])
|
|
575
|
+
const colorC = triangleMeshColor(node.props.colors[indices[offset + 2] as number])
|
|
576
|
+
if (!colorA || !colorB || !colorC) continue
|
|
577
|
+
fillColoredTriangle(context, a, b, c, [colorA, colorB, colorC])
|
|
578
|
+
} else {
|
|
579
|
+
trianglePath(context, a, b, c)
|
|
580
|
+
context.fill()
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return
|
|
584
|
+
}
|
|
216
585
|
default:
|
|
217
586
|
unhandledShape(node, 'the Canvas2D renderer')
|
|
218
587
|
}
|
|
@@ -226,6 +595,7 @@ export function renderCanvas2D(
|
|
|
226
595
|
context: CanvasRenderingContext2D,
|
|
227
596
|
scene: CanvasScene,
|
|
228
597
|
viewport: CanvasViewport,
|
|
598
|
+
textureImage?: CanvasTextureImage,
|
|
229
599
|
) {
|
|
230
600
|
const pixelRatio = Math.max(1, viewport.pixelRatio || 1)
|
|
231
601
|
context.setTransform(1, 0, 0, 1, 0, 0)
|
|
@@ -252,7 +622,7 @@ export function renderCanvas2D(
|
|
|
252
622
|
context.translate(-viewBox[0], -viewBox[1])
|
|
253
623
|
}
|
|
254
624
|
}
|
|
255
|
-
for (const node of scene) drawNode(context, node)
|
|
625
|
+
for (const node of scene) drawNode(context, node, textureImage)
|
|
256
626
|
} finally {
|
|
257
627
|
context.restore()
|
|
258
628
|
}
|