【问题标题】:R-Shiny: How to display an animation and the controls created using saveHTML() function?R-Shiny:如何显示使用 saveHTML() 函数创建的动画和控件?
【发布时间】:2021-11-26 05:27:26
【问题描述】:

我在 R 中制作了一个 HTML 小部件,它使用如下 saveHTML 函数通过一系列 png 图像进行动画处理:

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")

这会在我的工作目录中创建一个名为 index.html 的 html 对象。当我双击它时,会打开一个 Internet 浏览器,然后我使用控件来对“images”文件夹中的 .png 文件进行动画处理。

我的问题是,我如何在 R 闪亮的应用程序中呈现它?

【问题讨论】:

  • 您可以使用 iframe 将生成的 html 文件嵌入到闪亮的应用程序中。在这样做之前,您需要通过将其放在 www 文件夹中或使用 addResourcePath 来使 Shiny 的 Web 服务器可以使用此资源。请检查我的回答here

标签: javascript html r shiny


【解决方案1】:

我的第一个想法是使用includeHTML,但很快就会遇到文件路径问题。一个快速的解决方法是使用&lt;iframe&gt;(各有利弊)。您所要做的就是确保保存的HTML 的文件夹和图片文件夹在shiny 中是已知的。最简单的方法是放置图片和预定义的www 文件夹(已知)并添加root 作为资源:

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(...) {})

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 1970-01-01
    • 2015-10-12
    • 2019-02-11
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多