Plotly to image

by ravidixit

HTML

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://cdn.jsdelivr.net/canvg/1.4.0/canvg.js"></script>
<script src="https://cdn.jsdelivr.net/canvg/1.4.0/rgbcolor.min.js"></script>
<script src="https://cdn.jsdelivr.net/canvg/1.4.0/canvg.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stackblur-canvas/1.4.0/stackblur.min.js"></script>
<body>
  <button id="btnShow">Show Plotly Graph Image</button>
  <div id="plotly_div"></div>
  <canvas id="imageCanvas" width="1000px" height="1600px"></canvas>
</body>

JavaScript

$(document).ready(function() {

  var d3 = Plotly.d3;
  var canvas = document.getElementById('imageCanvas');
  var context = canvas.getContext('2d');
  var graph_image = new Image();

  var someVariable = "";

  // Ploting the Graph
  var trace = {
    x: [3, 9, 8, 10, 4, 6, 5],
    y: [5, 7, 6, 7, 8, 9, 8],
    type: "scatter"
  };
  var trace1 = {
    x: [3, 4, 1, 6, 8, 9, 5],
    y: [4, 2, 5, 2, 1, 7, 3],
    type: "scatter"
  };
  var data = [trace, trace1];

  var layout = {
    title: "Simple Javascript Graph"
  };

  $("#btnShow").click(function() {

    context.drawImage(graph_image, 0, 0);

  });


  Plotly.plot(
      'plotly_div',
      data,
      layout)
    .then(
      function(gd) {
        Plotly.toImage(gd, {
            height: 500,
            width: 700
          })
          .then(
            function(url) {
              graph_image.src = url;
              return Plotly.toImage(gd, {
                format: 'svg',
                height: 800,
                width: 800
              });
            })

      });
});