Skip to content

ugly example of converting sunburst to png #120

@timelyportfolio

Description

@timelyportfolio

Here is a very ugly example using fabric.js to convert the sunburst to a png. Note, this only converts the main chart and not the breadcrumbs and legends.

library(htmltools)
library(sunburstR)

sequences <- read.csv(
  system.file("examples/visit-sequences.csv",package="sunburstR")
  ,header = FALSE
  ,stringsAsFactors = FALSE
)[1:100,]


browsable(
  tagList(
    tags$head(
      tags$script(src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/index.min.js")
    ),
    tags$div(tags$button(onclick = "convertToPng()", "convert to png")),
    sunburst(sequences, elementId = "sunburst-chart", height = 600, width = 800), 
    tags$canvas(id="canvas", height = 600, width = 800),
    tags$script(HTML(
"
  function convertToPng() {
    // Get the SVG element
    const svgElement = document.querySelector('#sunburst-chart .sunburst-chart svg');
    
    // add css from css style directly to svg
    const elements = document.querySelectorAll('.sunburst-chart path')
    
    elements.forEach(element => {
      element.style.stroke = '#fff';
    });

    // Serialize the SVG element to a string
    const svgString = new XMLSerializer().serializeToString(svgElement);

    // Create a Fabric.js canvas
    const canvas = new fabric.Canvas('canvas');
    
    fabric.loadSVGFromString(svgString).then(({ objects }) => {
      var obj = fabric.util.groupSVGElements(objects);
      canvas.add(obj);
      canvas.renderAll();
      
      // Convert the canvas to a PNG data URL
      const pngDataUrl = canvas.toDataURL('image/png');
      
      // Download image
      var alink = document.createElement('a');
      alink.download = 'sunburst_image.png';
      // Attach the data to the link
      alink.href = pngDataUrl;
      // Get the code to click the download link
      alink.click();
    });
  }
"      
    ))
  )
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions