r4ds / mastering_shiny_book_solutions

https://mastering-shiny-solutions.org
Creative Commons Zero v1.0 Universal
19 stars 6 forks source link

A better answer for question 1 in chapter 9 #39

Open arashHaratian opened 3 years ago

arashHaratian commented 3 years ago
library(shiny)
library(ambient)
ui <- fluidPage(
  imageOutput("image_output"),
  actionButton("generate", "Generate an image"),
  downloadButton("download", "downlaod the image")
)

server <- function(input, output, session) {
  noise <- NULL
  grid <- NULL

  image <- eventReactive(input$generate,{
    noise <<- noise_worley(c(100, 100))
    grid <<- long_grid(seq(1, 10, length.out = 1000), seq(1, 10, length.out = 1000))
    grid$noise <<- gen_worley(grid$x, grid$y, value = 'distance')
    dir <- paste0(tempdir(),"/noise.png")
    png(dir)
    plot(grid, noise)
    dev.off()

    dir
  })

  output$image_output <- renderImage({

    list(src = image())
  })

  output$download <- downloadHandler(
    filename = "noise.png",
    content = function(file){
      png(file)
      plot(grid, noise)
      dev.off()
    }
  )
}

shinyApp(ui, server)
MayaGans commented 3 years ago

Hi @arashHaratian you mentioned this was for question 1 but I think the solution we provide, outside of Shiny, may be more in line with the prompt?

Use the ambient package by Thomas Lin Pedersen to generate worley noise and download a PNG of it.

Is this maybe referring to another question in the chapter?

arashHaratian commented 3 years ago

no. I think the question asks us to make an app to download the generated noise (to use download functionality in shiny), not to open a graphics device and save it manually.

MayaGans commented 3 years ago

Hmm that does make sense to me, what do you think, @marlycormar ?