block by timelyportfolio 7456dca7c174f14e9827d7437a4fd0c2

d3 brush + svg textLength experiment in R

Full Screen

Built with blockbuilder.org

Replicate this CodePen experiment in R using htmltools from RStudio. I think not enough people know how helpful htmltools can be.

library(htmltools)

browsable(
  attachDependencies(
    tagList(
      tags$head(
        tags$style(
'
.brush .extent {
  stroke: #000;
  fill-opacity: .125;
  shape-rendering: crispEdges;
}
'
        )
      ),
      tags$div(
        HTML('Use <code>d3.svg.brush</code> to squish and stretch
             with the <a href = 
             "https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/textLength"
             ><code>textLength</code></a> attribute'
        )
      ),
      tag(
        'svg',
        list(
          width="800px",
          height="100px",
          tag(
            "text",
            list(
              x="0", y="0", dy="1em", textLength="500px",
              lengthAdjust="spacingAndGlyphs", "font-size"="3em",
              "squish and stretch"
            )
          )
        )
      ),
      tags$script(
HTML('
var svg = d3.select("svg");
var width = svg.node().getBoundingClientRect().width;
var height = svg.node().getBoundingClientRect().height;
var x = d3.scale.linear()
.range([0,width-1])
.domain([0,width-1]);

var textel = svg.select("text");

function brush_fun() {
var x0 = brush.extent()[0];
var x1 = brush.extent()[1];

textel.transition().duration(1000)
.attr("x",x0)
.attr("textLength",x1-x0);
};

var brush = d3.svg.brush()
.x(x)
.extent([0,width/2])
.on("brush", brush_fun);

var brush_g = svg.append("g")
.attr("class", "brush")
.call(brush);

brush_g.selectAll("rect")
.style("height", height-2);

brush_fun();
')        
      )
    ),
    htmlDependency(
      name="d3js",
      version="3.5.5",
      src=c(href="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5"),
      script="d3.min.js"
    )
  )
)

index.html