我使用了这个页面的函数
https://github.com/hafen/trelliscope/blob/master/R/thumb.R,并尝试简化它。
你需要安装来自
http://phantomjs.org/download.html的PhantomJS,并将路径设置为环境变量。
该函数如下(参数
p
是HTML小部件,
thumbName
是新的.png文件的名称):
library(htmlwidgets)
widgetThumbnail <- function(p, thumbName, width = 1024, height = 768) {
phantom <- findPhantom()
success <- FALSE
if(phantom == "") {
message("** phantomjs dependency could not be found - thumbnail cannot be generated (run phantomInstall() for details)")
} else {
res <- try({
ff <- paste0(thumbName, ".html")
ffjs <- paste0(thumbName, ".js")
p$sizingPolicy$padding <- 0
suppressMessages(saveWidget(p, ff, selfcontained = FALSE))
js <- paste0("var page = require('webpage').create();
page.viewportSize = { width: ", width,", height: ", height," };
page.clipRect = { top: 0, left: 0, width: ", width,", height: ", height," };
page.open('", ff, "', function(status) {
console.log(\"Status: \" + status);
if(status === \"success\") {
page.render('", thumbName, ".png');
}
phantom.exit();
});")
cat(js, file = ffjs)
system2(phantom, ffjs)
})
if(!inherits(res, "try-error")) {
success <- TRUE
}
if(!file.exists(paste0(thumbName, ".png"))) {
success <- FALSE
}
}
if(!success) {
message("** could not create htmlwidget thumbnail... creating an empty thumbnail...")
}
}
phantomInstall <- function() {
message("Please visit this page to install phantomjs on your system: http://phantomjs.org/download.html")
}
findPhantom <- function() {
phantom <- Sys.which("phantomjs")
if(Sys.which("phantomjs") == "") {
if(identical(.Platform$OS.type, "windows")) {
phantom <- Sys.which(file.path(Sys.getenv("APPDATA"), "npm", "phantomjs.cmd"))
}
}
phantom
}
它会创建一个.js文件,可以将你的html小部件截屏,并将.js、.html和.png文件保存到活动目录中。
library(networkD3)
src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)
plot = simpleNetwork(networkData)
widgetThumbnail(p = plot, thumbName = "plot", height = 500)
RSelenium
包将为您完成它... - Spacedman