Line data Source code
1 : import type { CompactSize as CanvasSize } from '@comfyorg/shared-frontend-utils/geometry'
2 : import { clamp } from 'es-toolkit'
3 :
4 : import type { Transform } from '#/node'
5 : import { drawPlacedInto, placedBounds } from './bake'
6 : import type { Bitmap } from './place'
7 :
8 2 : const CLIPPED_LAYER_PREVIEW_OPACITY = 0.4
9 :
10 : export interface OutsideCanvasPreviewLayer {
11 : bitmap: Bitmap
12 : opacity: number
13 : transform: Transform
14 : }
15 :
16 7 : function extendsOutsideCanvas(
17 : transform: Transform,
18 : canvas: CanvasSize
19 : ): boolean {
20 7 : const bounds = placedBounds(transform)
21 7 : return (
22 : bounds.x < 0 ||
23 : bounds.y < 0 ||
24 : bounds.x + bounds.w > canvas.w ||
25 : bounds.y + bounds.h > canvas.h
26 : )
27 : }
28 :
29 11 : export function drawOutsideCanvasPreview(
30 : ctx: CanvasRenderingContext2D,
31 : canvas: CanvasSize,
32 : layers: OutsideCanvasPreviewLayer[]
33 : ): void {
34 11 : const clippedLayers = layers.filter(
35 : (layer) =>
36 : layer.opacity > 0 && extendsOutsideCanvas(layer.transform, canvas)
37 : )
38 11 : if (!clippedLayers.length) return
39 :
40 0 : try {
41 0 : for (const layer of clippedLayers) {
42 0 : ctx.save()
43 0 : try {
44 0 : ctx.globalAlpha =
45 : CLIPPED_LAYER_PREVIEW_OPACITY * clamp(layer.opacity, 0, 1)
46 0 : drawPlacedInto(ctx, layer.bitmap, layer.transform, 0, 0)
47 : } finally {
48 0 : ctx.restore()
49 : }
50 : }
51 : } finally {
52 0 : ctx.clearRect(0, 0, canvas.w, canvas.h)
53 : }
54 : }
|