Rectangle border around SVG text

前端 未结 2 400
春和景丽
春和景丽 2021-01-02 09:24

Trying to put a border around some SVG text, and I am getting varying results.

HTML: (with the mute class)



        
相关标签:
2条回答
  • 2021-01-02 10:06

    To draw a rect around text on click, 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 d.x;})
            .y(function(d){return d.y;})
            .interpolate("linear"); 
        // Draw the line
        svgcanvas.append("svg:path")
            .attr("d", d3line(pathinfo))
            .style("stroke-width", 1)
            .style("stroke", "red")
            .style("fill", "none");
    
    })
    

    On 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>
    
    0 讨论(0)
  • 2021-01-02 10:10

    SVG elements don't support the CSS border property as you have discovered. Your options are

    1. Draw a red <rect> around the text as a border
    2. Put a border on the outer <svg> element if its parent is a html element. The outer <svg> element is a replaced element and will support the CSS border property.
    0 讨论(0)
提交回复
热议问题