Rectangular frame around SVG text

Trying to put a border around some SVG text, and I get different results.

HTML: (with dumb class)

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <text x="37.5" y="37.5" class="ablate-x mute">X</text> </svg> 

CSS

 .ablate-x { font-size: 24px; color: gray; opacity: 0.5; font-weight: 900; cursor: hand; cursor: pointer; } .mute { opacity: 1; fill: red; stroke: red; stroke-width: 2px; /* we tried border: 2px solid red; but it didn't work */ } 

D3.js:

 .on("click", function(d) { var selection = d3.select(this); selection.classed("mute", (selection.classed("mute") ? false : true)); }) 

Here we have X without a mute class gray

Here we have X with a dumb class red but no frame

This is what we are trying to get the border to look like red with border

Note: its parent is a group, not an HTML element.

JS Fiddle: http://jsfiddle.net/chrisfrisina/yuRyr/5/

+7
source share
2 answers

SVG elements do not support the CSS border property, as you discovered. Your options

  • Draw a red <rect> around the text as a border
  • Place the border on the external <svg> element if its parent element is an html element. The external <svg> element is a replaced element and will support the CSS border property.
+11
source

To draw a rectangle around the text when clicked, update the code to:

 var svgcanvas = d3.select('svg'); $("#xc").on("click", function (d) { var selection = d3.select(this); var rect = this.getBBox(); var offset = 2; // enlarge rect box 2 px on left & right side selection.classed("mute", (selection.classed("mute") ? false : true)); pathinfo = [ {x: rect.x-offset, y: rect.y }, {x: rect.x+offset + rect.width, y: rect.y}, {x: rect.x+offset + rect.width, y: rect.y + rect.height }, {x: rect.x-offset, y: rect.y + rect.height}, {x: rect.x-offset, y: rect.y }, ]; // Specify the function for generating path data var d3line = d3.svg.line() .x(function(d){return dx;}) .y(function(d){return dy;}) .interpolate("linear"); // Draw the line svgcanvas.append("svg:path") .attr("d", d3line(pathinfo)) .style("stroke-width", 1) .style("stroke", "red") .style("fill", "none"); }) 

In this html:

  <!DOCTYPE html> <html> <head> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <svg width="720" height="720"> <text x="37.5" y="37.5" id="xc">X</text> </svg> </body> </html> 
+9
source

All Articles