Basj
Basj

Reputation: 46371

Plotly "toImage": send the image to server instead of triggering a browser file download

I'd like the top bar "Download plot as a png" button to send the image data to server (for example via Javascript fetch) instead of triggering a browser file download.

I see there are Plotly.toImage and Plotly.downloadImage that could be used, but how to redefine the standard "Download plot as a png" button to do that?

Plotly.newPlot('myDiv', [{x: [1, 2, 3, 4], y: [10, 15, 13, 17], mode: 'markers'}]);
<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="myDiv"></div>

Upvotes: 3

Views: 894

Answers (1)

sungryeol
sungryeol

Reputation: 4005

Solution: how to redefine the standard "Download plot as a png" button to do that?

Please check out this code snippet. The image save button has been removed and a custom send image button has added. The button will get image as base64. it is up to you how to send the image.

Following parts of official plotly.js docs are used as reference:

const layout = {}
const btnCapture = {
  name: 'send image',
  icon: Plotly.Icons.camera,
  direction: 'up',
  click: async(gd) => {
    const imgBase64 = await Plotly.toImage(gd, {
      width: 300,
      height: 300
    })
    console.log('do something with image', imgBase64)
    console.log(Plotly.Icons)
  }
}
const config = {
  modeBarButtonsToAdd: [btnCapture],
  modeBarButtonsToRemove: ['toImage']
}


Plotly.newPlot('myDiv', [{
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  mode: 'markers',
}], layout, config)
<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="myDiv"></div>

Upvotes: 2

Related Questions