rsvgshinysvgpanzoom

How to pan and zoom svg file in shiny app


I have the shiny app below in which I want to pan and zoom the .svg.

library(shiny)
library(DiagrammeR)
library(tidyverse)
# probably don't need all of these:
library(DiagrammeRsvg)
library(svglite)
library(svgPanZoom)
library(rsvg)
library(V8)# only for svg export but also does not work
library(xml2)

ui <- fluidPage(
  grVizOutput("grr",width = "100%",height = "90vh")
)

server <- function(input, output) {
  
  
  
  reactives <- reactiveValues()
  observe({
    reactives$graph <- render_graph(create_graph() %>%
                                      add_n_nodes(n = 2) %>%
                                      add_edge(
                                        from = 1,
                                        to = 2,
                                        edge_data = edge_data(
                                          value = 4.3)))
  })
  output$grr <-
    renderGrViz(reactives$graph
    )
  
}

# Run the application
shinyApp(ui = ui, server = server)

I tried with the svgPanZoom package but could make it work. How does this work? Or an alternative option?

ui <- fluidPage(
  svgPanZoomOutput("grr")
)

server <- function(input, output) {
  
  
  
  reactives <- reactiveValues()
  observe({
    reactives$graph <- render_graph(create_graph() %>%
                                      add_n_nodes(n = 2) %>%
                                      add_edge(
                                        from = 1,
                                        to = 2,
                                        edge_data = edge_data(
                                          value = 4.3)))
  })
  output$grr <-
    renderSvgPanZoom({
      svgPanZoom(reactives$graph)
      
    })
  
}

# Run the application
shinyApp(ui = ui, server = server)

Solution

  • You can use the panzoom JavaScript library.

    library(shiny)
    library(DiagrammeR)
    library(magrittr)
    
    ui <- fluidPage(
      tags$head(
        tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js")
      ),
    
      grVizOutput("grr", width = "100%", height = "90vh"),
    
      tags$script(
        HTML('panzoom($("#grr")[0])')
      )
    )
    
    server <- function(input, output) {
    
      reactives <- reactiveValues()
    
      observe({
        reactives$graph <- render_graph(create_graph() %>%
                                          add_n_nodes(n = 2) %>%
                                          add_edge(
                                            from = 1,
                                            to = 2,
                                            edge_data = edge_data(
                                              value = 4.3)))
      })
    
      output$grr <- renderGrViz(reactives$graph)
    
    }
    
    shinyApp(ui, server)