首页 > 解决方案 > Adjusting the height and width of a screenshot with html2canvas?

问题描述

I'd like to remove the highlighted yellow portion in the bottom, which should make the important parts of the png biggerand more clear. Here is a reproducible example. I have tried adding in the height and width options, shown here, but they don't affect my screenshot. Is this because I'm using body as the element? I'd like to just remove the bottom of my shinyapp from the screenshot. As you can probably tell, I am new to javascript and coding in general, and any help is greatly appreciated.

library(shiny)
library(shinyjs)
library(DT)
library(ggplot2)

ui <- fluidPage(
  tags$head(
    # include html2canvas library
    tags$script(src = "http://html2canvas.hertzen.com/dist/html2canvas.min.js"),
    # script for creating the prompt for download
    tags$script(
      "
            function saveAs(uri, filename) {

                var link = document.createElement('a');

                if (typeof link.download === 'string') {

                    link.href = uri;
                    link.download = filename;

                    //Firefox requires the link to be in the body
                    document.body.appendChild(link);

                    //simulate click
                    link.click();

                    //remove the link when done
                    document.body.removeChild(link);

                } else {

                    window.open(uri);

                }
            }
            "
    )
  ),
  useShinyjs(),
  actionButton("screenshot","Take Screenshot"),
  dataTableOutput("table"),
  plotOutput("plot")


)

server <- function(input, output, session) {
  observeEvent(input$screenshot,{
    shinyjs::runjs(
      'html2canvas(document.querySelector("body")).then(canvas => {
                saveAs(canvas.toDataURL(), "shinyapp.png");
           });'
    )
  })


  output$table <- renderDataTable(iris)

  output$plot <- renderPlot(ggplot(data = iris) + 
                              geom_point(aes(x = Sepal.Length, y = Sepal.Width)))
}

shinyApp(ui, server)

标签: javascriptshinyhtml2canvasshinyapps

解决方案


不确定从屏幕截图中删除我的 shinyapp 底部是什么意思。这是一个仅将表格或绘图图像打印为屏幕截图的工作示例。

# To print only the table in the screenshot
shinyjs::runjs(
      'html2canvas(document.querySelector("table")).then(canvas => {
                saveAs(canvas.toDataURL(), "shinyapp.png");
           });')

# To print only the image in the screenshot
shinyjs::runjs(
      'html2canvas(document.querySelector("img")).then(canvas => {
                saveAs(canvas.toDataURL(), "shinyapp.png");
           });')

希望这可以帮助!


推荐阅读