我想知道用户何时在shiny 的应用程序中单击图像.我的完整应用程序在一种"照片搜寻"游戏中显示图像,我想捕捉用户点击每张图像中相关位置所需的时间.然而,我很难捕获客户端时间,这很重要,因为服务器端时间可能会由于各种原因而延迟.我想我需要下面的javascript之类的东西,但我不知道如何将其集成到应用程序中.
- 在页面上查找元素
var image = document.getElementById('img');
- 倾听点击并捕捉时间
addEventListener("click", true,
click_time = new Date().getTime();)
- 将捕获的时间发送到shiny server,如下所示:
Shiny.onInputChange("new_click_time",click_time);
- 收听shiny以获取click\u时间
observeEvent(input$new_click_time,{
# This should be the time the user clicked on the image:
input$new_click_time
})
下面是一个获得服务器时间而非客户端时间的shiny 应用程序示例:
library(shiny)
library(shinyjs)
options(digits.secs = 3) # Modify default global time to show milleseconds
shinyApp(
ui = fluidPage(
useShinyjs(),
sidebarLayout(
sidebarPanel(
p("When clicking on the histogram, I'd like to capture the client-side computer's time"),
actionButton(inputId="new_image", label= "New Image")
),
mainPanel(
imageOutput("img", click = "photo_click"),
textOutput("client_time"),
textOutput("server_time")
)
)
),
server = function(input, output) {
output$img <- renderImage({
input$new_image
outfile <- tempfile(fileext='.png')
png(outfile, width=400, height=400)
hist(rnorm(100))
dev.off()
list(src = outfile,
alt = "This is alternate text")
},
deleteFile = TRUE)
output$server_time <- renderText({
req(input$photo_click)
server.time <- as.character(strptime(Sys.time(), "%Y-%m-%d %H:%M:%OS")) # Time with milliseconds
paste("SERVER TIME:", server.time)
})
output$client_time <- renderText({
# cat("\nI'd like to capture click-time, possibly here -- the time on the client's machine when a click is made")
req(input$photo_click)
client.time <- "???" # Time with milliseconds
paste("CLIENT TIME:", client.time)
})
}
)