MCPcopy
hub / github.com/canvg/canvg / measureTargetText

Method measureTargetText

src/Document/TextElement.ts:487–536  ·  view source on GitHub ↗
(
    ctx: RenderingContext2D,
    targetText: string
  )

Source from the content-addressed store, hash-verified

485 }
486
487 protected measureTargetText(
488 ctx: RenderingContext2D,
489 targetText: string
490 ) {
491 if (!targetText.length) {
492 return 0
493 }
494
495 const { parent } = this
496 const customFont = parent.getStyle('font-family').getDefinition<FontElement>()
497
498 if (customFont) {
499 const fontSize = this.getFontSize()
500 const text = customFont.isRTL
501 ? targetText.split('').reverse().join('')
502 : targetText
503 const dx = toNumbers(parent.getAttribute('dx').getString())
504 const len = text.length
505 let measure = 0
506
507 for (let i = 0; i < len; i++) {
508 const glyph = this.getGlyph(customFont, text, i)
509
510 measure += (glyph.horizAdvX || customFont.horizAdvX)
511 * fontSize
512 / customFont.fontFace.unitsPerEm
513
514 if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) {
515 measure += dx[i]
516 }
517 }
518
519 return measure
520 }
521
522 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
523 if (!ctx.measureText) {
524 return targetText.length * 10
525 }
526
527 ctx.save()
528 this.setContext(ctx, true)
529
530 const { width: measure } = ctx.measureText(targetText)
531
532 this.clearContext(ctx)
533 ctx.restore()
534
535 return measure
536 }
537
538 /**
539 * Inherits positional attributes from {@link TextElement} parent(s). Attributes

Callers 2

measureTextMethod · 0.95
measureTextMethod · 0.80

Calls 9

getFontSizeMethod · 0.95
getGlyphMethod · 0.95
setContextMethod · 0.95
toNumbersFunction · 0.90
getDefinitionMethod · 0.80
splitMethod · 0.80
getStringMethod · 0.80
clearContextMethod · 0.80
measureTextMethod · 0.45

Tested by

no test coverage detected