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.4/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>
Step 2: add an an element to the page:
<div id="calculator" style="width: 300px; height: 300px;"></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.
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.
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 |
This will update or create a mathematical expression. expression_state should be an object which represents a single expression. Provided below is a table of supported options for the expression_state argument.
Name | Values |
---|---|
id | String, required. Should be a valid property name for a javascript object (letters, numbers, and _). |
latex | String, required, following Desmos Expressions. |
color | String, hex color. See Colors. Default will cycle through 6 default colors. |
hidden | Boolean, which determines if graph is drawn. Defaults to false. |
If setExpression
is called on an id which 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).
This function does not return any value.
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'});
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. id is missing), this function will have no effect.
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.
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'});
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);
});
Updates the dimensions of the calculator. bounds must be an array of four numbers, interpreted as [xmin, xmax, ymin, ymax]
If invalid dimensions are provided (xmin < xmax
, ymin < ymax
, or the wrong number of arguments), the dimensions of the viewport will not be changed.
Examples:
//Only show the first quadrant
calculator.setViewport([0, 10, 0, 10]);
This function does not return any value.
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.
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 width and height 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);
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
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();
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.
When analyzed, expressions can cause one or more of the following effects:
If the expression can be evaluated to a number, it will be evaluated
If the expression expresses one variable as a function of another, it will be plotted.
If the expression defines one or more points, they will be plotted directly.
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.
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.
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.
If the input cannot be interpreted, the expression will be marked as an error.
Here are a few examples:
input | effect |
---|---|
Evaluable. | |
Plots y as a function of x. | |
Defines m as a variable that can be referenced by other expressions. | |
Plots a as a function of x, and defines a as a variable that can be referenced by other expressions. | |
Plots an implicit curve of x and y. |
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:
+, -, *, /, ^
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.
) 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.
e, pi
\pi
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:
, and shorthand notation: . 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
and . 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.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
\sqrt{x}
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 an observe
method that allows you to observe their value, which might change in response to a user editing an expression or sliding a slider.
a.observe('numericValue', function () {
console.log(a.numericValue);
});
The callback will be called every time the value of the helper expression changes. numericValue
is currently the only observable property of helper expressions, but other observable properties may be added in the future.
See examples/helper.html for an example of monitoring the value of a slider and using it to update the surrouding page.
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'
});
Returns the hex string representation of the next color in the default color list.
Below is a basic example which adjusts the amplitude phase of a sin curve as the user moves their mouse in the window
<script type='text/javascript'>
var elt = document.getElementById('calculator');
var calculator = Desmos.Calculator(elt);
calculator.setExpressions([
{id:'1', latex:'a=1'},
{id:'2', latex:'b=1'},
{id:'3', latex:'y=b\\sin(x+a)', color: Desmos.Colors.GREEN}
]);
var updateVariable = function (evt) {
calculator.setExpression({id:'1', latex:'a='+(evt.pageX/100)});
calculator.setExpression({id:'2', latex:'b='+(evt.pageY/100)});
};
// Register the callback as a listener on mousemove, and use it to
// update the values of a and b.
document.addEventListener('mousemove', updateVariable, true);
</script>
See examples/mousemove.html to see this example live.
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.
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.4/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.