Skip to content

Commit

Permalink
✨ Add stroke support for Text layer
Browse files Browse the repository at this point in the history
  • Loading branch information
Flandia Yingman committed Aug 13, 2023
1 parent ccd6c55 commit 513af9f
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/layer/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ interface TextOptions extends VisualOptions {
* @see [`CanvasRenderingContext2D#direction`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline)
*/
textDirection?: Dynamic<string>

textStroke?: Dynamic<{
color: Color,
position?: 'inside' | 'center' | 'outside'
thickness?: number
}>
}

class Text extends Visual {
Expand All @@ -49,6 +55,11 @@ class Text extends Visual {
* @see [`CanvasRenderingContext2D#direction`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline)
*/
textDirection: Dynamic<string>
textStroke?: Dynamic<{
color: Color,
position?: 'inside' | 'center' | 'outside'
thickness?: number
}>

private _prevText: string
private _prevFont: string
Expand Down Expand Up @@ -94,6 +105,34 @@ class Text extends Visual {
maxWidth
)

const textStroke = val(this, 'textStroke', this.currentTime)
if (textStroke) {
this.cctx.strokeStyle = textStroke.color
this.cctx.lineWidth = textStroke.thickness ?? 1
const position = textStroke.position ?? 'outer'
// Save the globalCompositeOperation, we have to revert it after stroking the text.
const globalCompositionOperation = this.cctx.globalCompositeOperation
switch (position) {
case 'inside':
this.cctx.globalCompositeOperation = 'source-atop'
this.cctx.lineWidth *= 2
break
case 'center':
break
case 'outside':
this.cctx.globalCompositeOperation = 'destination-over'
this.cctx.lineWidth *= 2
break
}
this.cctx.strokeText(
text,
val(this, 'textX', this.currentTime),
val(this, 'textY', this.currentTime),
maxWidth
)
this.cctx.globalCompositeOperation = globalCompositionOperation
}

this._prevText = text
this._prevFont = font
this._prevMaxWidth = maxWidth
Expand Down Expand Up @@ -137,7 +176,8 @@ class Text extends Visual {
maxWidth: null,
textAlign: 'start',
textBaseline: 'top',
textDirection: 'ltr'
textDirection: 'ltr',
textStroke: null
}
}
}
Expand Down

0 comments on commit 513af9f

Please sign in to comment.