R Shiny:如何将vtree htmlwidget截图存为PNG?shinyscreenshot未捕获部件
问题:Shiny中vtree生成的可视化无法被shinyscreenshot捕获
在Shiny应用里,用vtree生成的htmlwidget可视化组件,使用shinyscreenshot工具截图时,只能捕获页面其他部分,无法抓取到vtree的内容,已在Firefox和Edge浏览器测试过。应用代码如下:
library(shiny) library(vtree) library(shinyscreenshot) # Define UI ---- ui <- pageWithSidebar( # App title ---- headerPanel("Cyl vtree"), # Sidebar panel for inputs ---- sidebarPanel( screenshotButton(selector = "body") ), # Main panel for displaying outputs ---- mainPanel( vtreeOutput("VTREE", height = "800px") ) ) # Define server logic to plot ---- server <- function(input, output) { output[["VTREE"]] <- renderVtree({ vtree(mtcars, "cyl") }) } shinyApp(ui, server)
解决方案
shinyscreenshot基于html2canvas实现,对部分依赖SVG渲染的htmlwidget(比如vtree)支持有限,推荐改用webshot2工具,它能更可靠地捕获网页中的可视化元素。
步骤1:安装并加载依赖包
install.packages("webshot2") library(shiny) library(vtree) library(webshot2)
步骤2:修改Shiny应用代码
ui <- pageWithSidebar( headerPanel("Cyl vtree"), sidebarPanel( actionButton("save_screenshot", "保存vtree截图") ), mainPanel( vtreeOutput("VTREE", height = "800px") ) ) server <- function(input, output) { output[["VTREE"]] <- renderVtree({ vtree(mtcars, "cyl") }) # 点击按钮触发截图 observeEvent(input$save_screenshot, { webshot2::webshot( url = shiny::getUrl(), # 获取当前Shiny应用的URL file = "vtree_screenshot.png", # 保存的文件名 selector = "#VTREE", # 指定捕获vtree的容器 vwidth = 1200, # 截图宽度 vheight = 800 # 截图高度 ) }) } shinyApp(ui, server)
说明
webshot2通过直接定位DOM元素(#VTREE是vtree输出容器的ID)来捕获内容,能正确识别SVG渲染的vtree组件。- 首次使用
webshot2可能需要安装浏览器驱动,运行webshot2::install_phantomjs()即可完成依赖安装,或者根据控制台提示安装对应浏览器的驱动。
内容的提问来源于stack exchange,提问作者TarJae
相关产品推荐
相关产品推荐

