[英]export plotly as self-contained html in JavaScript
In JavaScript, how to export plotly plot as a self-contained html file?在 JavaScript 中,如何将绘图导出为独立的 html 文件? Just like in R, we can use
saveWidget
function.就像在 R 中一样,我们可以使用
saveWidget
函数。 How to do it with JavaScript?如何用 JavaScript 做到这一点?
Edit编辑
I tried to use我试着用
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "export.html";
a.href = "data:text/html," + document.getElementById("myDiv").innerHTML;
a.click();
But it does work well because it loses all the event, etc.但它确实运行良好,因为它丢失了所有事件等。
https://codepen.io/anon/pen/XqZqWX https://codepen.io/anon/pen/XqZqWX
You can download plotly.js
and then call Plotly.newPlot method.你可以下载
plotly.js
然后调用Plotly.newPlot方法。
Here are step details.以下是步骤详细信息。
async function getPlotlyScript() {
// fetch
const plotlyRes = await fetch('https://cdn.plot.ly/plotly-latest.js')
// get response as text
return await plotlyRes.text()
}
We need to pass the current chart state in Plot.newPlot
method.我们需要在
Plot.newPlot
方法中传递当前图表状态。 If the chart data and layout are not controlled by your code, don't worry.如果图表数据和布局不受您的代码控制,请不要担心。 The DOM element where plotly builds the chart contains
data
and layout
.绘制图表的 DOM 元素包含
data
和layout
。
function getChartState () {
const el = document.getElementById('your plotly container id')
return {
data: el.data, // current data
layout: el.layout // current layout
}
}
Now we have everything to compose our HTML.现在我们拥有了编写 HTML 所需的一切。 Don't forget to:
不要忘记:
charset="utf-8"
because plotly script has special characters.charset="utf-8"
因为情节脚本有特殊字符。async function getHtml() {
const plotlyModuleText = await getPlotlyScript()
const state = getChartState()
return `
<head>
<meta charset="utf-8" />
</head>
<script type="text/javascript">
${plotlyModuleText}
<\/script>
<div id="plotly-output"></div>
<script type="text/javascript">
Plotly.newPlot(
'plotly-output',
${JSON.stringify(state.data)},
${JSON.stringify(state.layout)}
)
<\/script>
`
}
async function exportToHtml () {
// Create URL
const blob = new Blob([await getHtml()], { type: 'text/html' })
const url = URL.createObjectURL(blob)
// Create downloader
const downloader = document.createElement('a')
downloader.href = url
downloader.download = 'export.html'
// Trigger click
downloader.click()
// Clean up
URL.revokeObjectURL(url)
}
exportToHtml()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.