All examples By author By category About

timelyportfolio

fabric.js + ggplot2 with svg

Built with blockbuilder.org

Jeroen Ooms asked if we could just use the svg directly with fabric.js after I posted this fabric.js + ggplot2 example. I answered yes, but I learned the answer should have been almost.

I thought it might be the CDATA that is interfering, but I gsub-bed it out and still the not quite right.

Not sure I'm up for it, but adding the style to the document might work, or we could emply a technique similar to svg-crowbar which appends styles directly to each element.

library(ggplot2)
library(svglite)
library(rsvg)
library(fabricjsR)
library(htmltools)

# try to make a ggplot
#  get svg with svglite
#  convert svg to png
#  draw on fabric.js canvas
s <- svgstring(standalone=FALSE)
ggplot(data.frame(y=sin(1:10)), aes(x=1:10,y=y)) + geom_smooth()
s()
dev.off()

browsable(
  attachDependencies(
    tagList(
      tags$canvas(id="c", height="500", width="500"),
      tags$script(sprintf(
"
var canvas = new fabric.Canvas('c');
fabric.loadSVGFromURL(
  %s,
  function(objects,options){
    var obj = fabric.util.groupSVGElements(objects, options);
    canvas.add(obj).renderAll();
  }
)
"       ,
        shQuote(
          paste0(
            "data:image/svg+xml,",
            shiny:::URLencode(
              gsub(x=s(),pattern="(.*)(<!\\[CDATA\\[)(.*)(\\]\\]>)(.*)","\\1\\3\\5")
            )
          )
        )
      ))
    ),
    htmlwidgets:::widget_dependencies("fabric","fabricjsR")[[2]]
  )
)