@hozo/canvas 0.1.0 → 0.3.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.
@@ -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 drawNode(context: CanvasRenderingContext2D, node: CanvasSceneNode) {
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
  }