首页 > 解决方案 > 如何将自动播放按钮添加到闪亮的应用程序

问题描述

我正在编写一个闪亮的应用程序,它加载一系列图像(即帧)并包含一个“自动播放”按钮来自动浏览所有图像。

这是代码相关部分的 MRE 版本。自动播放按钮是作为 UI 对象间接生成的,因为还涉及到一个动态帧选择滑块。可以在此处获得示例 PNG 文件。

library(shiny)
ui <- fluidPage(
    sidebarPanel(uiOutput("play")), # autoplay button
    mainPanel(imageOutput("image_frame"))
)
server <- function(input, output) {
    frame <- reactiveValues(out=1, autoplay=FALSE)
    # Finding where the images are stored and what their names are ---
    image <- reactive({
        file_path <- "~" # Home folder on Linux
        file_list <- list.files(file_path, pattern="*.png")
        return(list(path=file_path, name=file_list))
    })
    # Determining which frame will be printed ------------------------
    tot_frames <- reactive(length(image()$name))
    output$play <- renderUI(actionButton("play", "Autoplay"))
    observeEvent(input$play, {
        frame$autoplay <- TRUE
        frame$out <- 1:tot_frames()
    })
    # Printing selected frame ----------------------------------------
    frame_path_to_print <- reactive({
        filename <- image()$name[frame$out]
        out <- paste0(image()$path, filename)
        return(out)
    })
    # This is how I intuitively think it should work, except it doesn't
    if (isolate(frame$autoplay)) {
        for (f in isolate(frame$out)) {
            output$image_frame <- list(
                src=paste0(image()$path, image()$name[f])
            )
            Sys.sleep(0.1)
        }
    } else {
        output$image_frame <- renderImage(
            list(src=frame_path_to_print())
        )
    }
}
shinyApp(ui, server)

我已经成功地添加了“上一个”和“下一个”按钮,但我无法让“自动播放”按钮工作。除了上面的代码之外,我还尝试了几件事,比如让它在循环或 *apply 函数上调用与“下一步”按钮相同的操作,我尝试将它们放在服务器函数的几个位置,但没有任何效果。我仍然对反应式环境的工作方式感到有些困惑,所以如果我知道这根本不是这样做的方式,我不会感到惊讶,但我在 Internet 上找不到任何关于它的信息。

标签: rimageshinyreactive

解决方案


因此,即使我已经为此工作了好几天,但幸运的是,我刚刚找到了一个来自相关问题的解决方案。

诀窍是该sliderInput函数包含一个animate参数,当设置为 时TRUE,会添加一个自动通过帧的播放按钮。更多信息在这里

我仍然对涉及工作自动播放按钮而不是不同 UI 对象上的小按钮的其他解决方案感到好奇。


推荐阅读