【发布时间】:2021-01-10 08:56:29
【问题描述】:
我对将 Javascript 与 R 相结合的世界很陌生,而且我的 Javascript 知识非常有限。我正在尝试制作一个plotly 国际象棋开局图,当您单击开局时,它会显示一个带有开局初始移动的棋盘。
library(plotly)
library(htmlwidgets)
library(data.table)
library(rchess)
data("chessopenings")
setDT(chessopenings)
mychess = chessopenings[1:10]
mychess[, Pop := sample(c(1,2,4), nrow(mychess), replace = T)]
mychess[, fens := sapply(pgn, function(x) {chsspgn <- Chess$new(); chsspgn$load_pgn(x); chsspgn$fen()})]
上面的代码只是创建了一个包含 10 个开口的示例数据集。然后,我根据我在https://plotly-r.com/supplying-custom-data.html#fig:hover-annotate 找到的指导,使用 plotly 绘制它们,我尝试创建一个新函数,当您单击点时显示棋盘。 棋盘函数是此处指定的函数https://chessboardjs.com/examples#1002,如果我理解正确(如果我错了,请纠正我)它会返回一个“div”元素,这是我必须显示的元素。
q = plot_ly(mychess, x = ~eco, y = ~Pop) %>%
add_markers(text = ~name,
customdata = ~fens)
onRender(
q, "
function(el) {
el.on('plotly_click', function(d) {
var pt = d.points[0];
var fen = d.points[0].customdata
var newboard = Chessboard('myBoard', fen);
newboard.style.visibility = 'visible';
newboard.style.display = 'block';
})}")
不幸的是,没有任何显示。我使用了这里提供的信息Show/hide 'div' using JavaScript,但似乎我遗漏了一些东西。
更新:我尝试了@Bas 的建议,使用以下代码转换图像:
png(pic1 <- tempfile(fileext = ".png"));chessboardjs(fen = mychess$fens[1]); dev.off()
text = knitr::image_uri(pic1)
text = sub(".*?,", "", text)
html <- sprintf('<html><body><img src="data:image/png;base64,%s"></body></html>', text)
cat(html, file = tf2 <- tempfile(fileext = ".html"))
browseURL(tf2)
但这也不起作用。
【问题讨论】:
标签: javascript r plotly r-plotly