Text

Element

Constructs a text element.

The coordinates can either be absolute (i.e. respective to the coordinate system of the board) or be relative to the coordinates of an element given in Text#anchor.

HTML, MathJaX, KaTeX, ASCIIMathML, and GEONExT syntax can be handled.

Internally, there are two ways to display texts:

  • using the text element of the renderer (canvas or svg). In most cases this is the suitable approach if speed matters. However, advanced rendering like MathJax, KaTeX or HTML/CSS are not possible.
  • using HTML <div>. This is the most flexible approach. The drawback is that HTML can only be display "above" the geometry elements. If HTML should be displayed in an inbetween layer, consider to use an element of type ForeignObject (available in SVG renderer, only).

This can be controlled with attribute Text#display that takes the values 'html' or 'internal'. In case of 'html' an HTML division tag is created to display the text. In this case it is also possible to use MathJax, KaTeX, or ASCIIMathML. If neither of these is used, basic Math rendering is applied.

In case of 'internal', an SVG text element is used to display the text.

Usage (signatures)
board.create('text', [zopt, x, y, str]);

Parent elements can be two or three elements of type number, a string containing a GEONExT constraint, or a function which takes no parameter and returns a number. Every parent element beside the last determines one coordinate. If a coordinate is given by a number, the number determines the initial position of a free text. If given by a string or a function that coordinate will be constrained that means the user won't be able to change the texts's position directly by mouse because it will be calculated automatically depending on the string or the function's return value. If two parent elements are given the coordinates will be interpreted as 2D affine Euclidean coordinates, if three such parent elements are given they will be interpreted as homogeneous coordinates.

The text to display may be given as string or as function returning a string.

Parameters
Name Type Attributes Default Description
z NumberLike <optional>
1
x NumberLike
y NumberLike
str String | function

String to be displayed. Could be the return value of a function, to make the text dynamic.

Examples
// Create a fixed text at position [0,1].
  var t1 = board.create('text',[0,1,"Hello World"]);
// Create a variable text at a variable position.
  var s = board.create('slider',[[0,4],[3,4],[-2,0,2]]);
  var graph = board.create('text',
                       [function(x){ return s.Value();}, 1,
                        function(){return "The value of s is"+JXG.toFixed(s.Value(), 2);}
                       ]
                    );
// Create a text bound to the point A
var p = board.create('point',[0, 1]),
    t = board.create('text',[0, -1,"Hello World"], {anchor: p});

Attributes

Own

anchor

Description

Anchor element Point, Text or Image of the text. If it exists, the coordinates of the text are relative to this anchor element. In this case, only numbers are possible coordinates, functions are not supported.

Type
Object
Default Value
null
Example
var p = board.create('point', [0,1]);
board.create('text', [1, 0, 'message'], {anchor:p});

Source
options.js, line 10691

anchorX

Description

The horizontal alignment of the text. Possible values include 'auto', 'left', 'middle', and 'right'.

Type
String
Default Value
'left'
Source
options.js, line 10722

anchorY

Description

The vertical alignment of the text. Possible values include 'auto, 'top', 'middle', and 'bottom'. For MathJax or KaTeX, 'top' is recommended.

Type
String
Default Value
'middle'
Source
options.js, line 10734

attractors

Description

List of attractor elements. If the distance of the text is less than attractorDistance the text is made to glider of this element.

Type
Array
Default Value
empty
Source
options.js, line 10847

cssClass

Description

Apply CSS classes to the text in non-highlighted view. It is possible to supply one or more CSS classes separated by blanks.

Type
String
Overrides
JXG.Text#cssClass
Default Value
'JXGtext'
See
Source
options.js, line 10747

cssDefaultStyle

Description

Default CSS properties of the HTML text element.

The CSS properties which are set here, are handed over to the style property of the HTML text element. That means, they have higher property than any CSS class.

If a property which is set here should be overruled by a CSS class then this property should be removed here.

The reason, why this attribute should be kept to its default value at all, is that screen dumps of SVG boards with board.renderer.dumpToCanvas() will ignore the font-family if it is set in a CSS class. It has to be set explicitly as style attribute.

In summary, the order of priorities (specificity) from high to low is

  • JXG.Options.text.cssStyle
  • JXG.Options.text.cssDefaultStyle
  • JXG.Options.text.cssClass

If all texts should get its font-family from the default CSS class before initializing the board

  JXG.Options.text.cssDefaultStyle = '';
  JXG.Options.text.highlightCssDefaultStyle = '';

should be called.

Type
String
Default Value
'font-family: Arial, Helvetica, Geneva, sans-serif;'
See
Source
options.js, line 10193

cssStyle

Description

CSS properties of the HTML text element.

The CSS properties which are set here, are handed over to the style property of the HTML text element. That means, they have higher property (specificity) han any CSS class.

Type
String
Default Value
''
See
Source
options.js, line 10261

digits

Description

Used to round texts consisting solely of a number. Needs the attribute formatNumber:true.

Type
Number
Default Value
2
See
Source
options.js, line 10005

display

Description

Determines the rendering method of the text. Possible values include 'html' and 'internal'.

Type
String
Default Value
'html'
Source
options.js, line 10679

dragArea

Description

Sensitive area for dragging the text. Possible values are 'all', or something else. If set to 'small', a sensitivity margin at the right and left border is taken. This may be extended to left, right, ... in the future.

Type
String
Default Value
'all'
Source
options.js, line 10777

fontSize

Description

The font size in pixels.

Type
Number
Default Value
12
See
Source
options.js, line 9946

fontUnit

Description

CSS unit for the font size of a text element. Usually, this will be the default value 'px' but for responsive application, also 'vw', 'vh', vmax', 'vmin' or 'rem' might be useful.

Type
String
Default Value
'px'
See
Example
var txt = board.create('text', [2, 2, "hello"], {fontSize: 8, fontUnit: 'vmin'});

Source
options.js, line 9958

formatNumber

Description

If the text content is solely a number and this attribute is true (default) then the number is either formatted according to the number of digits given by the attribute 'digits' or converted into a fraction if 'toFraction' is true.

Otherwise, display the raw number.

Type
Boolean
Default Value
false
See
Source
options.js, line 9986

highlightCssClass

Description

Apply CSS classes to the text in highlighted view. It is possible to supply one or more CSS classes separated by blanks.

Type
String
Overrides
JXG.Text#highlightCssClass
Default Value
'JXGtext'
See
Source
options.js, line 10762

highlightCssDefaultStyle

Description

Default CSS properties of the HTML text element in case of highlighting. The CSS properties which are set here, are handed over to the style property of the HTML text element. That means, they have higher property than any CSS class.

If all texts should get its font-family from the default CSS class before initializing the board

  JXG.Options.text.cssDefaultStyle = '';
  JXG.Options.text.highlightCssDefaultStyle = '';

should be called.

Type
String
Default Value
'font-family: Arial, Helvetica, Geneva, sans-serif;'
See
Source
options.js, line 10234

highlightCssStyle

Description

CSS properties of the HTML text element in case of highlighting.

The CSS properties which are set here, are handed over to the style property of the HTML text element. That means, they have higher property (specificity) than any CSS class.

Type
String
Default Value
''
See
Source
options.js, line 10279

intl

Description

Internationalization support for texts consisting of a number only.

Setting the local overwrites the board-wide locale set in the board attributes. The JSXGraph attribute digits is overruled by the Intl attributes "minimumFractionDigits" and "maximumFractionDigits". See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat for more information about possible options.

See below for an example where the text is composed from a string and a locale formatted number.

Type
object
Default Value
{
   enabled: 'inherit',
   options: {
     minimumFractionDigits: 0,
     maximumFractionDigits: 2
   }
}
See
Examples
var t = board.create('text', [1, 2, -Math.PI*100], {
        formatNumber: true,
        digits: 2,
        intl: {
                enabled: true,
                options: {
                    style: 'unit',
                    unit: 'celsius'
                }
            }
    });

var t = board.create('text', [0.05, -0.2, ''], {
    intl: {
        enabled: true,
        locale: 'it-IT',
        options: {
            style: 'unit',
            unit: 'kilometer-per-hour',
            unitDisplay: 'narrow',
            maximumFractionDigits: 2
        }
    }
});

// Set dynamic text consisting of text and number.
t.setText(function() {
    var txt = 'Speed: ',
        number = t.X();

    // Add formatted number to variable txt
    // with fallback if locale is not supported.
    if (t.useLocale()) {
        txt += t.formatNumberLocale(number);
    } else {
        txt += JXG.toFixed(number, 2);
    }
    return txt;
});

Source
options.js, line 10019

isLabel

Description

If enabled, the text will be handled as label. Intended for internal use.

Type
Boolean
Overrides
JXG.Text#isLabel
Default Value
false
Source
options.js, line 10178

katexMacros

Description

Object or function returning an object that contains macros for KaTeX.

Type
Object
Default Value
{}
Example

Globally apply macros to all text elements

JXG.Options.text.katexMacros = {'\\jxg': 'JSXGraph is awesome'};

const board = JXG.JSXGraph.initBoard('jxgbox', {
    boundingbox: [-2, 5, 8, -5], axis:true
});

// This macro only get applied to the p ('text') element
var p = board.create('text', [1, 0, '\\jsg \\sR '], { katexMacros: {'\\sR':'\\mathbb{R}'} });
Source
options.js, line 10629

parse

Description

If set to true, the text is parsed and evaluated. For labels parse==true results in converting names of the form k_a to subscripts. If the text is given by string and parse==true, the string is parsed as JessieCode expression.

Type
Boolean
Default Value
true
Source
options.js, line 10152

rotate

Description

Text rotation in degrees. Works for non-zero values only in combination with display=='internal'.

Type
Number
Default Value
0
Source
options.js, line 10792

snapSizeX

Description

Defines together with Text#snapSizeY the grid the text snaps on to. The text will only snap on integer multiples to snapSizeX in x and snapSizeY in y direction. If this value is equal to or less than 0, it will use the grid displayed by the major ticks of the default ticks of the default x axes of the board.

Type
Number
Default Value
1
See
Source
options.js, line 10811

snapSizeY

Description

Defines together with Text#snapSizeX the grid the text snaps on to. The text will only snap on integer multiples to snapSizeX in x and snapSizeY in y direction. If this value is equal to or less than 0, it will use the grid displayed by the major ticks of the default ticks of the default y axes of the board.

Type
Number
Default Value
1
See
Source
options.js, line 10829

toFraction

Description

Display number as integer + nominator / denominator. Needs also the setting formatNumber: true Works together with MathJax, KaTex or as plain text.

Type
Boolean
Default Value
false
See
Example
board.create('text', [2, 2, 2 / 7], { anchorY: 'top', fontSize: 24, toFraction: true, formatNumber: true, useMathjax: true });
board.create('text', [2, -2, 2 / 19], { toFraction: true, formatNumber: true, useMathjax: false });

Source
options.js, line 10650

useASCIIMathML

Description

If true, the input will be given to ASCIIMathML before rendering.

Type
Boolean
Default Value
false
Source
options.js, line 10299

useCaja

Description

If set to true and caja's sanitizeHTML function can be found it will be used to sanitize text output.

Type
Boolean
Default Value
false
Source
options.js, line 10166

useKatex

Description

If true, KaTeX will be used to render the input string. For this feature, katex.min.js and katex.min.css have to be included.

The example below does not work, because there is a conflict with the MathJax library which is used below.

Type
Boolean
Default Value
false
Example
JXG.Options.text.useKatex = true;

const board = JXG.JSXGraph.initBoard('jxgbox', {
    boundingbox: [-2, 5, 8, -5], axis:true
});

var a = board.create('slider',[[-0.7,1.5],[5,1.5],[0,0.5,1]], {
    suffixlabel:'t_1=',
    unitLabel: ' \\text{ ms}',
    snapWidth:0.01});

func = board.create('functiongraph',[function(x){return (a.Value()*x*x)}], {strokeColor: "red"});
text1 = board.create('text', [5, 1, function(){
            return 'a(t)= { 1 \\over ' + a.Value().toFixed(3) + '}';
        }], {fontSize: 15, fixed:true, strokeColor:'red', anchorY: 'top'});

Source
options.js, line 10571

useMathJax

Description

If true, MathJax will be used to render the input string. Supports MathJax 2 and above. It is recommended to use this option together with the option parse: false. Otherwise, 4 backslashes (e.g. \\\\alpha) are needed instead of two (e.g. \\alpha).

Type
Boolean
Default Value
false
See
Examples
// Before loading MathJax, it can be configured like this:
<script>
    MathJax = {
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        displayMath: {'[+]': [['$$', '$$']]},
        packages: ['base', 'ams']
      }
    };
</script>
// Then, MathJax is loaded:
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg.js" id="MathJax-script"></script>

// Here is the JSXGraph part:
// Display style
board.create('text',[ 2,2,  function(){return '$$X=\\frac{2}{x}$$'}], {
    fontSize: 15, color:'green', useMathJax: true});

// Inline style
board.create('text',[-2,2,  function(){return '$X_A=\\frac{2}{x}$'}], {
    fontSize: 15, color:'green', useMathJax: true});

var A = board.create('point', [-2, 0]);
var B = board.create('point', [1, 0]);
var C = board.create('point', [0, 1]);

var graph = board.create('ellipse', [A, B, C], {
        fixed: true,
        withLabel: true,
        strokeColor: 'black',
        strokeWidth: 2,
        fillColor: '#cccccc',
        fillOpacity: 0.3,
        highlightStrokeColor: 'red',
        highlightStrokeWidth: 3,
        name: '$1=\\frac{(x-h)^2}{a^2}+\\frac{(y-k)^2}{b^2}$',
        label: {useMathJax: true}
    });

var nvect1 = board.create('text', [-4, -3, '\\[\\overrightarrow{V}\\]'],
{
  fontSize: 24, parse: false, useMathJax: true
});
var nvect1 = board.create('text', [-2, -4, function() {return '$\\overrightarrow{G}$';}],
{
  fontSize: 24, useMathJax: true
});

// Load MathJax:
// <script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg.js"></script>

// function and its derivative
var f1 = function(x) { return x * x * x; },
    graph1 = board.create('functiongraph', [f1, -0.1, 1.1]),

    A = board.create('glider', [0.5, f1(0.5), graph1], {
            name: 'f(x)',
            color: 'black',
            face:'x',
            fixed: true,
            size: 3,
            label: {offset: [-30, 10], fontSize: 15}
        }),
    B = board.create('glider', [0.7, f1(0.7), graph1], {
            name: 'f(x+Δx)',
            size: 3,
            label: {offset: [-60, 10], fontSize: 15}
        }),

    secant_line = board.create('line', [A,B],{dash: 1, color: 'green'}),
    a_h_segment = board.create('segment', [A, [
                    function(){ return B.X() > A.X() ? B.X() : A.X()},
                    function(){ return B.X() > A.X() ? A.Y() : B.Y()}
                ]],{ name: 'Δx', dash: 1, color: 'black'}),

    b_v_segment = board.create('segment', [B, [
                    function(){ return B.X() > A.X() ? B.X() : A.X()},
                    function(){ return B.X() > A.X() ? A.Y() : B.Y()}
                ]],{ name: 'Δy', dash: 1, color: 'black'}),

    ma = board.create('midpoint', [a_h_segment.point1, a_h_segment.point2], {visible: false});

board.create('text', [0, 0, function() {return '\\[\\Delta_x='+(B.X()-A.X()).toFixed(4)+'\\]'}], {
    anchor: ma, parse: false, useMathJax: true, fixed: true, color: 'green', anchorY: 'top'
});

var mb = board.create('midpoint', [b_v_segment.point1, b_v_segment.point2], {visible: false});

board.create('text', [0, 0, function() {return '\\[\\Delta_y='+(B.Y()-A.Y()).toFixed(4)+'\\]'}], {
    anchor: mb, parse: false, useMathJax: true, fixed: true, color: 'green'
});

var dval = board.create('text',[0.1, 0.8,
      function(){
        return '\\[\\frac{\\Delta_y}{\\Delta_x}=\\frac{' + ((B.Y()-A.Y()).toFixed(4)) + '}{' + ((B.X()-A.X()).toFixed(4)) +
            '}=' + (((B.Y()-A.Y()).toFixed(4))/((B.X()-A.X()).toFixed(4))).toFixed(4) + '\\]';
      }],{fontSize: 15, useMathJax: true});

var board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-1, 10, 11, -2], axis: true});
board.options.text.useMathjax = true;

var a = board.create('slider',[[-0.7,1.5],[5,1.5],[0,0.5,1]], {
    suffixlabel:'\\(t_1=\\)',
    unitLabel: ' \\(\\text{ ms}\\)',
    snapWidth:0.01}),

    func = board.create('functiongraph',[function(x){return (a.Value()*x*x)}], {strokeColor: "red"}),
    text1 = board.create('text', [5, 1, function(){
            return '\\(a(t)= { 1 \\over ' + a.Value().toFixed(3) + '}\\)';
        }], {fontSize: 15, fixed:true, strokeColor:'red', anchorY: 'top', parse: false});

Source
options.js, line 10310

visible

Type
Boolean
Overrides
JXG.Text#visible
Default Value
true
Source
options.js, line 10803

Inherited

Members

Own

none

Inherited

Methods

Own

none

Inherited

Coords

Dist

X

XEval

Y

YEval

Z

ZEval

_anim

_createFctUpdateText

_set

_setText

addAnchor

addChild

addConstraint

addDescendants

addParents

addParentsFromJCFunctions

addRotation

addTicks

addTransform

animate

bounds

calculateScore

checkForSizeUpdate

clearTrace

clearTransforms

cloneToBackground

convertGeonext2CSS

convertGeonextAndSketchometry2CSS

convertSketchometry2CSS

countChildren

createGradient

createLabel

crudeSizeEstimate

draggable

escapeTicks

eval

evalVisProp

expandShortMath

findClosestSnapValue

formatNumberLocale

free

fullUpdate

generatePolynomial

generateTerm

getAnchorX

getAnchorY

getAttribute

getAttributes

getLabelAnchor

getName

getNumberOfConflicts

getParents

getProperty

getSize

getSnapSizes

getTextAnchor

getType

handleAttractors

handleSnapToGrid

handleSnapToPoints

hasPoint

hide

hideElement

makeGlider

moveAlong

moveAlongES6

moveTo

moveToES6

noHighlight

normalize

notifyParents

poorMansTeX

popSlideObject

prepareUpdate

remove

removeAllTicks

removeChild

removeDescendants

removeTicks

removeTransform

replaceSub

replaceSup

resolveShortcuts

setArrow

setAttribute

setAutoPosition

setCoords

setDash

setDisplayRendNode

setGliderPosition

setLabel

setLabelText

setName

setParents

setPosition

setPositionByTransform

setPositionDirectly

setProperty

setText

setTextJessieCode

show

showElement

snapToPoints

toTopOfLayer

unescapeTicks

update

updateConstraint

updateCoords

updateGlider

updateGliderFromParent

updateRenderer

updateSize

updateText

updateTransform

updateVisibility

useLocale

utf8_decode

valueTagToJessieCode

visit

visitES6

Events

Own

none

Inherited

Details

Type
JXG.Text
See
Source
base/text.js, line 1598

Extends