繁体   English   中英

在 JavaScript 中将 plotly 导出为自包含的 html

[英]export plotly as self-contained html in JavaScript

在 JavaScript 中,如何将绘图导出为独立的 html 文件? 就像在 R 中一样,我们可以使用saveWidget函数。 如何用 JavaScript 做到这一点?

编辑

我试着用

var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("myDiv").innerHTML;
    a.click();

但它确实运行良好,因为它丢失了所有事件等。

https://codepen.io/anon/pen/XqZqWX

你可以下载plotly.js然后调用Plotly.newPlot方法。

以下是步骤详细信息。

获取情节脚本文本

async function getPlotlyScript() {
  // fetch
  const plotlyRes = await fetch('https://cdn.plot.ly/plotly-latest.js')
  // get response as text
  return await plotlyRes.text() 
} 

获取图表数据

我们需要在Plot.newPlot方法中传递当前图表状态。 如果图表数据和布局不受您的代码控制,请不要担心。 绘制图表的 DOM 元素包含datalayout

function getChartState () {
  const el = document.getElementById('your plotly container id')
  return {
    data: el.data, // current data
    layout: el.layout // current layout
  }
}

编写 HTML

现在我们拥有了编写 HTML 所需的一切。 不要忘记:

  • 添加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>
  `
}

下载 HTML 文件

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM