我使用了此页面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")
# don't want any padding
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...")
}
}
#' Get instructions on how to install phantomjs
#' @export
phantomInstall <- function() {
message("Please visit this page to install phantomjs on your system: http://phantomjs.org/download.html")
}
# similar to webshot
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 文件保存到活动目录中:
# Load package
library(networkD3)
# Create fake data
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
plot = simpleNetwork(networkData)
# Save html as png
widgetThumbnail(p = plot, thumbName = "plot", height = 500)