边缘测试.
library(shiny)
library(ggplot2)
js <- '
async function getImageBlobFromUrl(url) {
const fetchedImageData = await fetch(url);
const blob = await fetchedImageData.blob();
return blob;
}
$(document).ready(function () {
$("#copybtn").on("click", async () => {
const src = $("#plotDF>img").attr("src");
try {
const blob = await getImageBlobFromUrl(src);
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
alert("Image copied to clipboard!");
} catch (err) {
console.error(err.name, err.message);
alert("There was an error while copying image to clipboard :/");
}
});
});
'
ui <- fluidPage(
tags$head(
tags$script(HTML(js))
),
br(),
actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
br(),
plotOutput("plotDF")
)
server <- function(input, output, session){
output[["plotDF"]] <- renderPlot({
ggplot(
iris, aes(x = Sepal.Length, y = Sepal.Width)
) + geom_point()
})
}
shinyApp(ui, server)
EDIT
alert 不好.我建议改为shinyToastify英镑.
library(shiny)
library(shinyToastify)
library(ggplot2)
js <- '
async function getImageBlobFromUrl(url) {
const fetchedImageData = await fetch(url);
const blob = await fetchedImageData.blob();
return blob;
}
$(document).ready(function () {
$("#copybtn").on("click", async () => {
const src = $("#plotDF>img").attr("src");
try {
const blob = await getImageBlobFromUrl(src);
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
Shiny.setInputValue("success", true, {priority: "event"});
} catch (err) {
console.error(err.name, err.message);
Shiny.setInputValue("failure", true, {priority: "event"});
}
});
});
'
ui <- fluidPage(
tags$head(
tags$script(HTML(js))
),
useShinyToastify(),
br(),
actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
br(),
plotOutput("plotDF")
)
server <- function(input, output, session){
output[["plotDF"]] <- renderPlot({
ggplot(
iris, aes(x = Sepal.Length, y = Sepal.Width)
) + geom_point()
})
observeEvent(input[["success"]], {
showToast(
session,
input,
text = tags$span(
style = "color: white; font-size: 20px;", "Image copied!"
),
type = "success",
position = "top-center",
autoClose = 3000,
pauseOnFocusLoss = FALSE,
draggable = FALSE,
style = list(
border = "4px solid crimson",
boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
)
)
})
observeEvent(input[["failure"]], {
showToast(
session,
input,
text = tags$span(
style = "color: white; font-size: 20px;", "Failed to copy image!"
),
type = "error",
position = "top-center",
autoClose = 3000,
pauseOnFocusLoss = FALSE,
draggable = FALSE,
style = list(
border = "4px solid crimson",
boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
)
)
})
}
shinyApp(ui, server)