You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将htmlwidgets::onRender()渲染的动画保存为视频或GIF文件

Plotly 3D旋转动画导出为GIF/视频方案

方法1:导出为GIF格式

  • 首先安装所需依赖包:
    install.packages(c("plotly", "gifski", "png", "htmlwidgets", "webshot2"))
    
  • 逐帧渲染3D旋转画面并拼接为GIF,示例代码如下:
    library(plotly)
    library(gifski)
    library(htmlwidgets)
    library(webshot2)
    
    # 替换为你自己生成的3D绘图对象p
    p <- plot_ly(z = ~volcano, type = "surface") # 示例3D图
    
    n_frames <- 60 # 总帧数,数值越高动画越流畅、文件体积越大
    tmp_dir <- tempdir()
    
    # 循环生成不同视角的帧文件
    for (i in 1:n_frames) {
      # 配置3D镜头旋转参数
      cam <- list(
        eye = list(
          x = cos(2*pi*i/n_frames) * 1.5,
          y = sin(2*pi*i/n_frames) * 1.5,
          z = 0.5
        )
      )
      # 导出当前视角为png图片
      current_p <- p %>% layout(scene = list(camera = cam))
      saveWidget(current_p, "temp.html", selfcontained = FALSE)
      webshot("temp.html", file = file.path(tmp_dir, sprintf("frame_%03d.png", i)), vwidth = 800, vheight = 600)
    }
    
    # 拼接所有帧为GIF文件
    png_files <- list.files(tmp_dir, pattern = "frame_.*\\.png", full.names = TRUE)
    gifski(png_files, gif_file = "3d_rotate.gif", width = 800, height = 600, delay = 1/15)
    

方法2:导出为MP4等视频格式

  • 安装视频处理依赖:
    install.packages("av")
    
  • 拿到方法1中生成的所有png帧后,直接拼接为视频即可:
    library(av)
    av_encode_video(png_files, output = "3d_rotate.mp4", framerate = 15)
    
  • 可自行调整帧率、分辨率参数适配使用需求,修改output参数的后缀名即可导出mov、avi等其他常见视频格式。

内容的提问来源于stack exchange,提问作者leopold liu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:39:05