Skip to content

Commit 36373c8

Browse files
committed
utility function to draw inside of a masked clip rect
1 parent c9954a3 commit 36373c8

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/components/TextLabel.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ import { LayoutElement } from "../layout/LayoutElement";
44
export class TextLabel extends LayoutElement
55
{
66

7-
constructor( protected label:string )
7+
constructor( public label:string )
88
{
99
super();
10-
}
10+
}
1111

1212
override width(ctx: CanvasRenderingContext2D): number {
1313
ctx.font = this.fontSize+'px '+Theme.config.fontFamily
@@ -16,8 +16,8 @@ export class TextLabel extends LayoutElement
1616

1717
override renderContents(ctx: CanvasRenderingContext2D, maxWidth: number, maxHeight: number): void {
1818

19-
//text
20-
this.writeText(ctx, this.label, this.fontSize, 0, maxHeight, Theme.config.textColor );
21-
19+
this.drawClipped(ctx, maxWidth, maxHeight,
20+
()=>this.writeText(ctx, this.label, this.fontSize, 0, maxHeight, Theme.config.textColor )
21+
)
2222
}
2323
}

src/core/CanvasElement.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,22 @@ export class CanvasElement {
6565
}
6666
}
6767

68+
/**
69+
* Mask the draw to only be visible inside the square from 0,0 to width, height
70+
*/
71+
protected drawClipped(ctx: CanvasRenderingContext2D, width:number, height:number, draw:VoidFunction ){
72+
ctx.save()
73+
74+
try {
75+
76+
ctx.beginPath();
77+
ctx.rect(0, 0, width, height);
78+
ctx.clip();
79+
draw();
80+
81+
} finally {
82+
ctx.restore();
83+
}
84+
}
85+
6886
}

0 commit comments

Comments
 (0)