1

I've made a HTML widget in R that animates through a series of png images using the saveHTML function like this:

library(animation)

saveHTML({
    
    # List of the images in the 'images' directory
    image.list <- list.files('images', pattern = '*.png', full.names = TRUE)

    # Loop through and rename this for the animation to recognise it
    for (k in 1:length(image.list) ){
      
      file.rename(image.list[k], sprintf(ani.options('img.fmt'), k))
    }
       }
    , use.dev = FALSE, ani.width = 640, ani.height = 480, ani.type = 'png',
              interval = 2, single.opts = "'dwellMultiplier': 1")

This creates a html object called index.html in my working directory. When I double click this, an internet browser opens, and I use controls to animate through the .png files that were in the "images" folder.

My question is, how do I then render this in an R shiny App?

  • You can use an `iframe` to embed the resulting html file in your shiny app. Before doing so you'll need to make this resource available to shiny's web server by placing it in the www folder or using `addResourcePath`. Please check my answer [here](https://stackoverflow.com/questions/63823375/r-shiny-app-embedded-using-iframe-how-to-set-links-to-open-outside-the-iframe/63825034#63825034). – ismirsehregal Oct 06 '21 at 08:24

1 Answers1

0

My first idea was to use includeHTML, but then one quickly runs into issues with file paths. A quick workaround would be to use an <iframe> (with all it pros and cons). All you have to do is to make sure that the folder of the saved HTML and the picture folder is known in shiny. The easiest is to place pictures and the pre-defined www folder (which is known) and add the root as resource:

library(animation)
library(shiny)

tmpd <- tempdir()
tmpd <- gsub("\\\\", "/", tmpd)
tmpd <- file.path(tmpd, "animation")
if (!dir.exists(tmpd)) dir.create(tmpd)
tmpf <- file.path(tmpd, "random.html")

## use relative path for image dir
imgd <- "www"

## need to switch working dir such that: 
## saveHTML places the pics in the right location _AND_ uses relative paths
setwd(tmpd)

## A quick and dirty demo
des <- c("This is a silly example.\n\n", "You can describe it in more detail.", 
  "For example, bla bla...")
saveHTML({
  par(mar = c(4, 4, 0.5, 0.5))
  for (i in 1:20) {
    plot(runif(20), ylim = c(0, 1))
    ani.pause()
  }
}, img.name = "unif_plot", imgdir = imgd, htmlfile = tmpf, 
  autobrowse = FALSE, title = "Demo of 20 uniform random numbers", 
  description = des)

## add root dir as resource path
addResourcePath("animation", tmpd)

## include as iframe
shinyApp(fluidPage(tags$iframe(src="/animation/random.html", 
                               style = "height:99vh; width: 99vw; border:0")),
         function(...) {})
thothal
  • 16,690
  • 3
  • 36
  • 71