跳到主要内容

2D 图形

Desmos 的使用请前往 Desmos,本文档是在 Docusaurus 或网页中使用 Desmos API 的教程。

开始

如果你想在 Docusaurus 或网页绘制如下的精美图像,可以跟随教程,一步步实现。


第一步:绘图

2D 绘制 中绘制一个好看的图形,然后点击左下角“导出JSON”然后在控制台(通常点击“F12”可以打开)中复制JSON文本,类似于:

{"version":11,"randomSeed":"58e61c25066a0caae8932be9f504c4cc","graph":{"viewport":{"xmin":-10,"ymin":-6.461988304093566,"xmax":10,"ymax":6.423001949317738}},"expressions":{"list":[{"type":"expression","id":"1","color":"#c74440","latex":"x=y"},{"type":"expression","id":"2","color":"#2d70b3"}]},"includeFunctionParametersInRandomSeed":true,"doNotMigrateMovablePointStyle":true}

然后将其复制到一个 json 文件中,本教程复制到了“static/geo/json/desmos-2d.json”中。

第二步:创建 HTML 文件

复制以下 HTML 代码到文件中,如“static/geo/template/desmos-2d.html”:

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<script src="https://www.desmos.com/api/v1.11/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#calculator {
width: 100%;
height: 100vh;
border: none;
}
</style>
</head>
<body>
<div id="calculator"></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var elt = document.getElementById('calculator');
if (elt && window.Desmos) {
var calculator = Desmos.GraphingCalculator(elt, {
expressions: true,
expressionsCollapsed: false,
showGrid: true,
lockViewport: false,
expressionsCollapsed: true,
});
fetch('/geo/json/desmos-2d.json')
.then(response => {
return response.json();
})
.then(state => {
try {
calculator.setState(state);
} catch (error) {}
})
}
});
</script>
</body>
</html>

将32行中的目录替换为json所在目录。

fetch('/geo/json/desmos-2d.json')

第三步:插入代码块

Markdown

在 Markdown 中插入 iframe 嵌套第二步创建的网页:

<div style={{ borderRadius: '10px', overflow: 'hidden', aspectRatio: '3/2' }}>
<iframe
src="/geo/template/desmos-2d.html"
style={{ width: '100%', height: '100%', border: 'none' }}
/>
</div><br/>

网页

在网页中插入 iframe 嵌套第二步创建的网页:

<div style="border-radius: 10px; overflow: hidden; aspect-ratio: 3 / 2;">
<iframe
src="/geo/template/desmos-2d.html"
style="width: 100%; height: 100%; border: none;"
></iframe>
</div><br/>

第四步:欣赏


API

使用此 API 需要 key,本文档使用的为开发环境密钥,如需生产,请到 Desmos API 中详细阅读相关事宜。