Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Capture el tiempo del cliente al hacer clic en la imagen en la aplicación Shiny

Me gustaría saber cuándo un usuario hace clic en una imagen en una aplicación Shiny. Mi aplicación completa muestra imágenes en una especie de juego de "Photo Hunt" y quiero capturar cuánto tiempo le toma al usuario hacer clic en un lugar relevante en cada imagen. Sin embargo, tengo dificultades para capturar el tiempo del lado del cliente, lo cual es importante porque los tiempos del lado del servidor pueden retrasarse por varias razones. Creo que necesitaría algo como el siguiente javascript, pero no sé cómo integrarlo en la aplicación.

  1. Encuentra el elemento en la página.
 var image = document.getElementById('img');
  1. Escuche el clic y capture el tiempo
 addEventListener("click", true, click_time = new Date().getTime();)
  1. Envía el tiempo capturado al servidor brillante con algo como:
 Shiny.onInputChange("new_click_time",click_time);
  1. Escuche en brillante para obtener el click_time
 observeEvent(input$new_click_time,{ # This should be the time the user clicked on the image: input$new_click_time })

Aquí hay una aplicación brillante de ejemplo que obtiene la hora del servidor, pero no la hora del cliente:

 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) }) } )
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede usar la función javascript Shiny.setInputValue proporcionada por Shiny al cliente. Ejemplo:

 library(shiny) ui <- shiny::fluidPage( img(id = 'trigger_image', src = 'notfound.jpg', height = '100px', width = '100px' ), tags$script(' document.getElementById("trigger_image").onclick = function(){ var the_time = new Date().getTime(); // set input$client_time to the_time: Shiny.setInputValue("client_time", the_time)} ') ) server <- function(input, output) { observeEvent(input$client_time,{ ## do stuff with input$client_time }) } shinyApp(ui, server)

Tenga en cuenta que Javascript getTime devuelve milisegundos transcurridos desde 1970/1/1.

Brillante: comunicarse con Javascript

Editar

Si tiene que medir el tiempo transcurrido entre la actualización de la imagen en el cliente y la respuesta del usuario (haciendo clic en la imagen nueva), puede capturar y calcular la duración entre ambos eventos en el lado del cliente de esta manera:

 library(shiny) ui <- shiny::fluidPage( tags$script(' // ------ javascript code ------ // $(document).ready(...) ensures execution only after document is fully rendered // so that events like .onclick can be attached $(document).ready(function(){ // function to set Shiny input value to current time: const clockEvent = function(inputName){Shiny.setInputValue(inputName, new Date().getTime())} // trigger when the value of output id "trigger_image" changes: $(document).on("shiny:value", function(event){ if (event.target.id === "trigger_image") {clockEvent("displayed_at")} } ) // trigger when the image, after being sent or refreshed, is clicked: document.getElementById("trigger_image") .onclick = function(){clockEvent("reacted_at")} }) // ------------------------------ '), shiny::imageOutput('trigger_image'), actionButton('show_new', 'show new image'), textOutput('reaction_time') ) server <- function(input, output) { observeEvent(input$show_new,{ output$trigger_image <- shiny::renderImage(list(id = 'trigger_image', 'src' = 'image001.png' ), deleteFile = FALSE) output$reaction_time <- renderPrint(paste('reaction time (ms)', input$reacted_at - input$displayed_at)) }) } shinyApp(ui, server)
about 4 years ago · Juan Pablo Isaza Report

0

Lo siguiente parece capturar la hora del cliente, pero no veo cómo puede ser correcto, porque la hora del cliente es DESPUÉS de la hora del servidor.

 library(shiny) library(shinyjs) options(digits.secs = 3) # Modify and save default global time options click.time.image.js <- " document.getElementById('img').onclick = function(){ var the_time = new Date().getTime(); console.log(the_time); // set input$client_time to the_time: Shiny.setInputValue('client_time', the_time) } " 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() shinyjs::runjs(click.time.image.js) 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({ req(input$photo_click) req(input$client_time) client.time <- input$client_time # Time with milliseconds client.time <- as.POSIXct(client.time/1000, origin="1970-01-01") paste("CLIENTs TIME:", client.time) }) } )
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!