2

I'm having difficulty exporting a PNG of a dygraph in a Shiny app. I have been using this script following the example and modifying it for Shiny. I'm using the shinyjs library to pass my dygraph object to the client. I'm running into the following error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

Here is a hopefully reproducible example:

ui.R

library(shiny)
library(dygraphs)
library(shinyjs)

js.png <- '
  shinyjs.exportPNG = function(params) {
    var defaultParams = {
      dygraph : null,
      img : null,
      userOptions : null,
    }
    params = shinyjs.getParams(params, defaultParams);  

    var image = document.getElementById(params.img);
    Dygraph.Export.asPNG(params.dygraph, image);
  }
  '

shinyUI(fluidPage(
  useShinyjs(),
  extendShinyjs(text = js.png),
  actionButton('btn', 'Go'),
  includeScript('./www/dygraph-extra.js'),
  dygraphOutput("plot"),
  img(id = 'plot-static')
  )
)

server.R

library(dplyr)
library(xts)

shinyServer(function(input, output) {

  observeEvent(input$btn, {
    js$exportPNG(dygraph = dyplot.global, img = 'plot-static')
  })

  plot.data <- reactive({
    d <- airquality %>%
      mutate(Date = as.Date(paste('1973', Month, Day, sep = '-'))) %>%
      select(Date, Ozone, Temp) %>%
      arrange(Date)
    d.xts <- xts(d[,-1], order.by = d$Date)
  })

  output$plot <- renderDygraph({
    g <- dygraph(plot.data()) %>%
      dyRangeSelector()
    dyplot.global <<- g
    g
  })
})

I'm very novice with javascript, so please be gentle. The actual plot and data are quite a bit more involved and I'm pretty invested in the interaction and features in dygraphs. Thank you.

Sean Raffuse
  • 186
  • 8
  • I think dygraph creates html document, so this might help http://stackoverflow.com/questions/31336898/how-to-save-leaflet-in-rstudio-map-as-png-or-jpg-file – MLavoie Feb 19 '16 at 22:18
  • Thanks @MLavoie. That does work for exporting the dygraph as it initially looks when it is first loaded, but I would like to capture the view as the user sees it after zooming to their time period of interest. Perhaps this is not possible. – Sean Raffuse Feb 20 '16 at 00:59

0 Answers0