Quick Start

Desmos is the dead-simple way to embed rich, interactive math into your web page or web app. Here's how to draw an interactive graph in less than 60 seconds:

Step 1: include our secure javascript file:

<script src="https://www.desmos.com/api/v0.5/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>

Step 2: add an an element to the page:

<div id="calculator" style="width: 600px; height: 400px;"></div>

Step 3: add the following lines of javascript:

<script>
  var elt = document.getElementById('calculator');
  var calculator = Desmos.Calculator(elt);
  calculator.setExpression({id:'graph1', latex:'y=x^2'});
</script>

Step 4: Enjoy:

See examples/parabola.html to see this example live.

Preparing for production: In this example, we used the demo api key dcb31709b452b1cf9dc26972add0fda6. For production use, you should obtain your own api key and supply it as the apiKey parameter in the script url in step 1.

Calculator

The basic structure of the API is an embeddable Calculator, which is the page element which will display your axes, grid-lines, equations, and points.

Constructor

constructor Calculator(element, [options])

Creates a calculator object to control the calculator embedded in the DOM element specified by element.

Example:

var elt = document.getElementById('my-calculator');
var calculator = Desmos.Calculator(elt);

The object returned is a Desmos.Calculator object, which exposes methods for setting expressions, changing the viewport, etc.

options is an optional object that specifies features that should be included or excluded.

name default description
keypad true Show the onscreen keypad
graphpaper true Show the graphpaper
expressions true Show the expression list
settingsMenu true Show the settings wrench, for changing graph display
zoomButtons true Show onscreen zoom buttons
expressionsTopbar true Show the bar on top of the expressions list
solutions true Show solutions to solvable equations, and values when tracing
border true Add a subtle 1px gray border around the entire calculator
lockViewport false Disable user panning and zooming graphpaper
expressionsCollapsed false Collapse the expression list

Manipulating expressions

Calculator.setExpression(expression_state)

This will update or create a mathematical expression. expression_state should be an object which represents a single expression. Different types of expressions can be specified using the type property of expression_state, which must be either expression or table. If no type property is explicitly specified, the type defaults to expression. Further properties of expresison_state for each type are detailed below.

This function does not return any value.

Expressions
Name Values
type String 'expression', optional.
latex String, required, following Desmos Expressions.
color String hex color, optional. See Colors. Default will cycle through 6 default colors.
hidden Boolean, optional. Determines if graph is drawn. Defaults to false.
sliderBounds { min: Number, max: Number, step: Number }, optional. Set bounds of slider expressions. If step is omitted or undefined, the slider will be continuously adjustable.
domain { min: Number, max: Number }, optional. Set bounds of parametric curves.
id String, optional. Should be a valid property name for a javascript object (letters, numbers, and _).
Tables
Name Values
type String 'table', required.
columns Array of Table Columns, required.
id String, optional. Should be a valid property name for a javascript object (letters, numbers, and _).

If setExpression is called with an id that already exists, values for provided parameters will be updated in the expression, and unprovided parameters will remain unchanged (they will NOT be reset to default values).

Note: setExpression cannot be used to change the type of an existing expression. In that case, first use removeExpression to remove the existing expression.

If the expression results in an error, it will still be added to the expressions list, but nothing will be graphed.

If the provided parameters are invalid (e.g. type is set to something other than 'expression' or 'table'), this function will have no effect.

Examples:

//Define a variable m.  Doesn't graph anything.
calculator.setExpression({id: 'm', latex: 'm=2'});

//Draw a red line with slope of m through the origin.
//Because m = 2, this line will be of slope 2.
calculator.setExpression({id: 'line1', latex: 'y=mx', color='0xff0000'});

//Updating the value of m will change the slope of the line to 3
grapher.setExpression({id: 'm', latex: 'm=3'});

//Inequality to shade a circle at the origin
calculator.setExpression({id: 'circle1', latex: 'x^2 + y^2 < 1'});

//Restrict the slider for the m variable to the integers from 1 to 10
calculator.setExpression({id: 'm', sliderBounds: { min: 1, max: 10, step: 1}});
//Table with three columns. Note that the first two columns have explicitly
//specified values, and the third column is computed from the first.
calculator.setExpression({
  type: 'table',
  columns: [
    {
      latex: 'x',
      values: ['1', '2', '3', '4', '5']
    },
    {
      latex: 'y',
      values: ['1', '4', '9', '16', '25'],
      dragMode: Desmos.DragModes.XY
    },
    {
      latex: 'x^2',
      color: Desmos.Colors.BLUE,
      columnMode: Desmos.ColumnModes.LINES
    }
  ]
});

See this example live at examples/column-properties.html.

Additional Example:

Calculator.setExpressions(expression_states)

expression_states should be an array, and each element should be a valid argument for Calculator.setExpression()

This function will attempt to create expressions for each element in the array, and is equivalent to

expression_states.forEach(function(expression_state){
  calculator.setExpression(expression_state);
});

This function does not return any value.

Calculator.removeExpression(expression_state)

Remove an expression from the expression list. expression_state is an object with an id property.

Examples:

// Add an expression
calculator.setExpression({id: 'parabola', latex: 'y=x^2'});

// Remove it
calculator.removeExpression({id: 'parabola'});

Calculator.removeExpressions(expression_states)

Remove several expressions from the expression list. expression_states is an array of objects with id properties. This function is equivalent to

expression_states.forEach(function (expression_state) {
  calculator.removeExpression(expression_state);
});

Graph Settings

Calculator.setGraphSettings(graphSettings)

Updates graph display properties. graphSettings must be an object with properties from the following table. Only properties that are present will be changed–other settings will retain their previous value.

Setting Type Default Description
degreeMode Boolean false When true, trig functions assume arguments are in degrees. Otherwise, arguments are assumed to be in radians.
projectorMode Boolean false When true, fonts and line thicknesses are increased to aid legibility.
showGrid Boolean true Show or hide grid lines on the graph paper.
polarMode Boolean false When true, use a polar grid. Otherwise, use cartesian grid.
showXAxis Boolean true Show or hide the x axis.
showYAxis Boolean true Show or hide the y axis.
xAxisNumbers Boolean true Show or hide numeric tick labels on the x axis.
yAxisNumbers Boolean true Show or hide numeric tick labels on the y axis.
polarNumbers Boolean true Show or hide numeric tick labels at successive angles. Only relevant when polarMode is true.
xAxisStep Number 0 Spacing between numeric ticks on the x axis. Will be ignored if set too small to display. When set to 0, tick spacing is chosen automatically.
yAxisStep Number 0 Spacing between numeric ticks on the y axis. Will be ignored if set too small to display. When set to 0, tick spacing is chosen automatically.
xAxisMinorGridLines Number 0 Subdivisions between ticks on the x axis. Must be an integer between 0 and 5. 1 means that only the major grid lines will be shown. When set to 0, subdivisions are chosen automatically.
yAxisMinorGridLines Number 0 Subdivisions between ticks on the y axis. Must be an integer between 0 and 5. 1 means that only the major grid lines will be shown. When set to 0, subdivisions are chosen automatically.
xAxisArrowMode AxisArrowMode NONE Determines whether to place arrows at one or both ends of the x axis. See Axis Arrow Modes.
yAxisArrowMode AxisArrowMode NONE Determines whether to place arrows at one or both ends of the y axis. See Axis Arrow Modes
xAxisLabel String '' Label placed below the x axis.
yAxisLabel String '' Label placed beside the y axis.

Calculator.graphSettings

Object with observable properties for each graph setting.

Example:

// Set xAxisLabel
calculator.setGraphSettings({xAxisLabel: 'Time'});

// Observe the value of `xAxisLabel`, and log a message when it changes.
calculator.graphSettings.observe('xAxisLabel', function () {
  console.log(calculator.graphSettings.xAxisLabel);
});

See examples/graphsettings.html for a working example of setting and observing graph settings.

Axis Arrow Modes

The AxisArrowMode specifies whether arrows should be drawn at one or both ends of the x or y axes. It is specified separately for the x and y axes through the xAxisArrowMode and yAxisArrowMode graph settings. Must be one of

The default value for both axes is Desmos.AxisArrowMode.NONE.

Example:

// Set the x axis to have arrows on both ends
calculator.setGraphSettings({xAxisArrowMode: Desmos.AxisArrowModes.BOTH});

Coordinates

Calculator.setMathBounds(bounds)

Updates the math coordinates of the graphpaper bounds. bounds must be an object with left, right, bottom, and top properties.

If invalid bounds are provided (bounds.right <= bounds.left, bounds.top <= bounds.bottom), the graphpaper bounds will not be changed.

Example:

//Only show the first quadrant
calculator.setMathBounds({
  left: 0,
  right: 10,
  bottom: 0,
  top: 10
});

This function does not return any value.

Calculator.graphpaperBounds

The graphpaperBounds observable property gives the bounds of the graphpaper in both math coordinates and pixel coordinates. It is an object with the following structure:

{
  mathCoordinates: {
    top: Number,
    bottom: Number,
    left: Number,
    right: Number,
    width: Number,
    height: Number
  },
  pixelCoordinates: {
    top: Number,
    bottom: Number,
    left: Number,
    right: Number,
    width: Number,
    height: Number
  }
}

pixelCoordinates are referenced to the top left of the calculator's parent DOM element—that is, the element that is passed into the Calculator constructor. Note that pixelCoordinates.top < pixelCoordinates.bottom, but mathCoordinates.top > mathCoordinates.bottom.

Observing the graphpaperBounds property allows being notified whenever the graphpaper is panned or zoomed.

Example:

calculator.observe('graphpaperBounds', function () {
  var pixelCoordinates = calculator.graphpaperBounds.pixelCoordinates;
  var mathCoordinates = calculator.graphpaperBounds.mathCoordinates;

  var pixelsPerUnitY = pixelCoordinates.height/mathCoordinates.height;
  var pixelsPerUnitX = pixelCoordinates.width/mathCoordinates.width;

  console.log('Current aspect ratio: ' + pixelsPerUnitY/pixelsPerUnitX);
})

Calculator.mathToPixels(coords)

Convert math coordinates to pixel coordinates. coords is an object with an x property, a y property, or both. Returns an object with the same properties as coords.

Calculator.pixelsToMath(coords)

Convert pixel coordinates to math coordinates. Inverse of mathToPixels.

Examples:

// Find the pixel coordinates of the graphpaper origin:
calculator.mathToPixels({x: 0, y: 0});

// Find the math coordinates of the mouse
document.addEventListener('mousemove', function(evt) {
  console.log(calculator.pixelsToMath({x: evt.pageX, y: evt.pageY}));
});

Additional Examples:

Calculator.resize()

Resize the calculator to fill its container. This function should be called whenever the calculator container is resized using javascript. Note that we listen for changes to the size of the browser window, so you don't need to worry about size changes caused by window resize events, only those triggered by your javascript.

Example:

// Resize the calculator explicitly.
elt.style.width = '600px';
elt.style.height = '400px';
calculator.resize();

See examples/fullscreen.html for an example of how to keep the calculator resized to fill the full screen using absolute positioning.

This function does not return any value.

Selection and Focus

When an expression in the calculator is selected, its corresponding curve is highlighted. Expressions may be selected even when the expression list is not present. Currently, only one expression may be selected at a time, but in the future it may be possible to select more than one expression.

When an expression is focused, a cursor appears in it in the expression list, allowing the expression to be updated with the keypad or a keyboard. A focused expression is always selected, but an expression may be selected without being focused. Only one expression can be focused at a time.

Calculator.isAnyExpressionSelected

Boolean observable property, true when an expression is selected, false when no expressions are selected.

Calculator.removeSelected()

Remove the selected expression or expressions.

See examples/remove-selected.html for an example.

Calculator.focusedMathQuill

The focusedMathQuill observable property gives access to the currently focused mathquill object when there is one, allowing direct use of the Mathquill API. The value of this property is undefined when no expression is focused.

This can be used to implement math input mechanisms in addition to the Desmos onscreen keypad. See examples/custom-keypad.html.

Note that we are currently using the dev branch of Mathquill.

Saving and loading

Calculator.getState()

Returns a javascript object representing the current state of the calculator. Use in conjunction with Calculator.setState to save and restore calculator states.

The return value of Calculator.getState may be serialized to a string using JSON.stringify.

Warning: Calculator states should be treated as opaque values. Manipulating states directly may produce a result that cannot be loaded by Calculator.setState.

Calculator.setState(obj)

Reset the calculator to a state previously saved using Calculator.getState.

Calculator.setBlank()

Reset the calculator to a blank state.

Examples:

// Save the current state of a calculator instance
var state = calculator.getState();

// Use jQuery to post a state to your server for permanent storage
$.post('/myendpoint', JSON.stringify(state));

// Load a state into a calculator instance
calculator.setState(state);

// Reset the calculator to a blank state
calculator.setBlank();

Calculator.screenshot([_opts_])

Returns an image of the current graphpaper in the form of a png data uri.

opts is an optional object with opts.width and opts.height specifying the height and width of the screenshot in pixels. If height and width are not specified, the current height and width of the graphpaper will be used.

You can use the returned data uri directly in the src attribute of an image. To save the data as a traditional image file, you can parse the data and base64 decode it.

Examples:

// Capture a full size screenshot of the graphpaper
var fullsize = calculator.screenshot();

// Capture a 200px by 200px screenshot of the graphpaper
var thumbnail = calculator.screenshot({width: 200, height: 200});

// Append the thumbnail image to the current page
var img = document.createElement('img');
img.src = thumbnail;
document.body.appendChild(img);

Desmos Expressions

Expressions are the central mathematical objects used in Desmos. They can plot curves, draw points, define variables, even define multi-argument functions. Desmos uses latex for passing back and forth expressions.

The following sections give some examples of supported functionality but are not exhaustive.

We recommend using the interactive calculator at www.desmos.com/calculator to explore the full range of supported expressions.

Types of expressions

When analyzed, expressions can cause one or more of the following effects:

Evaluation

If the expression can be evaluated to a number, it will be evaluated

Plotting curves

If the expression expresses one variable as a function of another, it will be plotted.

Plotting points

If the expression defines one or more points, they will be plotted directly.

Plotting Inequalities

If an expression represents an inequality of x and y which can be solved, the entire region represented by the inequality will be shaded in.

Exporting definitions

Expression can export either variable or function definitions, which can be used elsewhere. Definitions are not order-dependent. Built in symbols cannot be redefined. If a symbol is defined multiple times, referencing it elsewhere will be an error.

Solving

If an expression of x and y can be solved (specifically, if it is quadratic in either x or y), the solution set will be plotted, but no definitions will be exported.

Errors

If the input cannot be interpreted, the expression will be marked as an error.

Here are a few examples:

input effect
1+1 Evaluable.
\sin(x) Plots y as a function of x.
m=1 Defines m as a variable that can be referenced by other expressions.
a=2+x Plots a as a function of x, and defines a as a variable that can be referenced by other expressions.
x+y=3 Plots an implicit curve of x and y.

Supported characters

Following the latex standard, all multi-character symbols must be preceded by a leading slash. Otherwise they will be interpreted as a series of single-letter variables.

The following functions are defined as built-ins:

Arithmetic operators

+, -, *, /, ^

These operators follow standard precedence rules, and can operate on any kind of expression. As specified by latex, exponentiation with a power that is more than one character (e.g. e^{2x}) require curly braces around the exponent.

Division is always represented in fraction notation. Curly braces can be used to specify the limits of the numerator and the denominator where they don't follow standard precendence rules.

Mathematical constants

e, pi

\pi is written as \pi

Trig functions (forward and inverse)

sin, cos, tan, cot, sec, csc, arcsin, arccos, arctan, arccot, arcsec, arccsc

These functions all take a single input, and operate in radians by default.

These functions support both formal function notation: \sin(x), and shorthand notation: \sin \space x. Shorthand notation is limited to cases where the provided argument is simple and unambiguous, so function notation is recommended for any computer-generated expressions.

These functions also support inverse and squared function notation, via \sin^{-1}(x) and \sin^2(x). This notation is not generally supported on most functions, but is provided for use with trig identities. For general use, disambiguating with parentheses is recommended.

Logarithms

ln, log

These functions both take a single input, and operate with bases of e, and 10, respectively. These work in both function and shorthand notation, like the trig functions.

Logs of arbitrary bases can be specified using using subscripts: \log_a(b) is interpreted as \log_a(b)

Square root

\sqrt{x} is written as \sqrt{x}

Helper Expressions

In addition to normal expressions that show up in the calculator's expression list, you can create “helper expressions” that are evaluated like normal expressions, but don't show up in the expression list. Helper expressions are useful for monitoring and reacting to what a user is doing with an embedded calculator. Every calculator object has a HelperExpression constructor for adding helper expressions to that calculator.

var calculator = Desmos.Calculator(elt);
calculator.setExpression({id: 'a-slider', latex: 'a=1'});
var a = calculator.HelperExpression({latex: 'a'});

Helper expressions have one observable property, numericValue that applies to expressions that evaluate to a number. It is updated whenever the expression changes.

HelperExpression.numericValue

a.observe('numericValue', function () {
  console.log(a.numericValue);
});

See examples/helper.html for an example of monitoring the value of a slider and using it to update the surrouding page.

Table Columns

Tables are specified by an array of their columns. The values in each column are either explicitly specified when the column header is a unique variable, or computed if the column header is an expression. The properties of table columns are given below:

Name Hex String
latex String, required. Variable or computed expression used in the column header.
values Array of latex strings, optional. Need not be specified in the case of computed table columns.
color String hex color, optional. See Colors. Default will cycle through 6 default colors.
hidden Boolean, optional. Determines if graph is drawn. Defaults to false.
columnMode Enum value, optional. See Column Modes. Defaults to Desmos.ColumnModes.POINT.
dragMode Enum value, optional. See Drag Modes. Defaults to DragModes.NONE.

Note that color, hidden, columnMode, and dragMode are ignored for the first column.

Column Modes

The columnMode of a table column determines whether points in the table column are drawn as points, lines, or both, specified as one of

Drag Modes

The dragMode of a table column determines whether the points in the table can changed by dragging in the x direction, the y direction, both, or neither, specified as

The dragMode is only applicable to explicitly specified column values, and has no effect on computed column values.

Colors

Colors are chosen from a default list of 6 colors. These are available through the Colors object.

Name Hex String
Colors.RED #C0504D
Colors.BLUE #4F81BD
Colors.GREEN #9BBB59
Colors.PURPLE #8064A2
Colors.ORANGE #F79646
Colors.BLACK #000000

You can choose the color of a new expression explicitly by setting it's color property.

Examples:

calculator.setExpression({
  id: '1',
  latex: 'y=x',
  color: Desmos.Colors.BLUE
});

calculator.setExpression({
  id: '2',
  latex: 'y=x + 1',
  color: '#ff0000'
});

Colors.next()

Returns the hex string representation of the next color in the default color list.

Collected Examples

Mathquill

Inside of the Desmos Calculator, we use mathquill for all of our equation rendering. We even use mathquill to render all of the math in this documentation. We're basically big fans of Mathquill. You can visit Mathquill at www.mathquill.com.

Release cycle

New versions of the calculator API are released in December and June on a six month scheduled release cycle. At any given time, there is an experimental preview version, a stable version that is recommended for production, and older versions are frozen.

Experimental: The embedded calculator exposed through the API will track changes to the www.desmos.com calculator in real time. In the Experimental version, we may make breaking changes to the API methods and to the calculator’s appearance at any time. The experimental version will generally be available for public preview and comment, but should not be used in production because of the possibility of breaking changes.

Stable: When a version of the API is stabilized, we will commit to not making any breaking changes to the API methods, and the embedded calculator will stop tracking changes to the www.desmos.com calculator. We think that it’s important that the visual appearance of the embedded calculator will not change once an API version is stabilized, because this gives our partners precise control over the appearance of their site. Important bug fixes that do not break compatibility are backported from Experimental to Stable.

The Stable version is the version that is recommended for production use.

Frozen: When a new version of the API is stabilized, the previous Stable version will become Frozen. This means that no future changes will be made to it, and it will not receive bug fixes. Partners are encouraged to migrate from Frozen versions to the Stable version in order to keep receiving bug fixes.

API Keys

In order to include the desmos api in your page, you must supply an api key as a url parameter, like this:

<script src="https://www.desmos.com/api/v0.5/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>

The demonstration api key, dcb31709b452b1cf9dc26972add0fda6, is provided for use during development. If you plan to use the api in production, you should contact us by e-mailing info@desmos.com to obtain your own api key.