简体   繁体   English

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

[英]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.以下是步骤详细信息。

Get plotly script text获取情节脚本文本

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

Get plotly chart data获取图表数据

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 元素包含datalayout

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

Compose HTML编写 HTML

Now we have everything to compose our HTML.现在我们拥有了编写 HTML 所需的一切。 Don't forget to:不要忘记:

  • add charset="utf-8" because plotly script has special characters.添加charset="utf-8"因为情节脚本有特殊字符。
  • escape closing script tag to make browser consider it as a string, not as a tag转义关闭脚本标签以使浏览器将其视为字符串,而不是标签
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>
  `
}

Download HTML document下载 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