Skip to content

Commit

Permalink
feat: Support letterSpacing for RTL.
Browse files Browse the repository at this point in the history
  • Loading branch information
xkxx committed Sep 12, 2023
1 parent 291a40d commit d7b86c5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/Context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ var COMMA = ',',
'strokeText',
'transform',
'translate',
'trySetLetterSpacing',
];

var CONTEXT_PROPERTIES = [
Expand All @@ -92,6 +93,11 @@ var CONTEXT_PROPERTIES = [
] as const;

const traceArrMax = 100;

interface CanvasRenderingContext2DFeatureDetection extends CanvasRenderingContext2D {
letterSpacing: string | undefined;
}

/**
* Konva wrapper around native 2d canvas context. It has almost the same API of 2d context with some additional functions.
* With core Konva shapes you don't need to use this object. But you will use it if you want to create
Expand Down Expand Up @@ -706,6 +712,21 @@ export class Context {
translate(x: number, y: number) {
this._context.translate(x, y);
}
/**
* Set letterSpacing if supported by browser.
* @method
* @name Konva.Context#trySetLetterSpacing
* @returns true if successful, false if not supported.
*/
trySetLetterSpacing(letterSpacing: number): boolean {
var context = this._context as CanvasRenderingContext2DFeatureDetection;
var letterSpacingSupported = 'letterSpacing' in context;

if (letterSpacingSupported) {
context.letterSpacing = letterSpacing + "px";
}
return letterSpacingSupported;
}
_enableTrace() {
var that = this,
len = CONTEXT_METHODS.length,
Expand Down
5 changes: 4 additions & 1 deletion src/shapes/Text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ var AUTO = 'auto',
PX_SPACE = 'px ',
SPACE = ' ',
RIGHT = 'right',
RTL = 'rtl',
WORD = 'word',
CHAR = 'char',
NONE = 'none',
Expand Down Expand Up @@ -213,6 +214,8 @@ export class Text extends Shape<TextConfig> {

context.setAttr('textAlign', LEFT);

var letterSpacingSupported = context.trySetLetterSpacing(letterSpacing);

// handle vertical alignment
if (verticalAlign === MIDDLE) {
alignY = (this.getHeight() - textArrLen * lineHeightPx - padding * 2) / 2;
Expand Down Expand Up @@ -288,7 +291,7 @@ export class Text extends Shape<TextConfig> {
context.stroke();
context.restore();
}
if (letterSpacing !== 0 || align === JUSTIFY) {
if ((letterSpacing !== 0 && !letterSpacingSupported) || align === JUSTIFY) {
// var words = text.split(' ');
spacesNumber = text.split(' ').length - 1;
var array = stringToArray(text);
Expand Down

0 comments on commit d7b86c5

Please sign in to comment.