繁体   English   中英

如何在 R Shiny 中使用 JavaScript 画一个圆?

[英]How do I draw a circle using JavaScript in R Shiny?

我希望在 R Shiny 中绘制简单的形状。(目标是使用 HTML 而不是加载 png 来绘制 static 图例。)

我无法使用 canvas 标签。 它根本不画任何东西。

library(shiny)

ui <- fluidPage(
  tags$script(HTML(
    "function draw_legend() {",
      "var canvas = document.getElementById('simple_legend');",
      "const canvas = document.getElementById('canvas');",
      "const ctx = canvas.getContext('2d');",
      "ctx.fillStyle = 'green';",
      "ctx.fillRect(10, 10, 150, 100);",
      "}"
  )),
  
  sidebarLayout(
    sidebarPanel(
    ),
    
    mainPanel(
      tags$body(onload="draw_legend();"),
      tags$canvas(id="simple_legend", height = "30"),
      tags$div("Some text")
    )
  )
)

server <- function(input, output, session) {
  
  
}

shinyApp(ui = ui, server = server)

扩展我的评论,这是一个应用程序,展示了在 Shiny 中绘制圆的两种技术,一种使用 CSS,另一种使用数据框。 您可以对尺寸、颜色、position 等进行明显调整以获得您想要的效果。

library(shiny)
library(tidyverse)

ui <-  fluidPage(
  tags$head(
    tags$style("#circleText {color: red; font-size: 20px; }")
  ),
  uiOutput("circleText"),
  plotOutput("circleGraph")
)

server <- function(input, output, session) {
  output$circleText <- renderUI({
    HTML("&#11044;")
  })
  
  output$circleGraph <- renderPlot({
    tibble(theta=seq(0, 2*pi, 0.025), x=sin(theta), y=cos(theta)) %>% 
      ggplot(aes(x, y)) +
        geom_path() +
        coord_fixed() +
        theme_void()
  },
  height=75,
  width=75)
}

shinyApp(ui = ui, server = server)

给予

在此处输入图像描述

你必须

  1. 删除行const canvas = document.getElementById('canvas');

  2. 为 canvas 元素设置宽度,而不仅仅是高度

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM