小编典典

SVG中文本的背景色

css

我想像在CSS中text一样给SVG的背景上色background-color

我只能找到有关的文档fill,该文档使文本本身着色

可能吗


阅读 1956

收藏
2020-05-16

共1个答案

小编典典

否,这是不可能的,SVG元素没有background-... 表示属性。

为了模拟这种效果,您可以使用fill="green"或类似的东西(过滤器)在text属性后面绘制一个矩形。使用JavaScript,您可以执行以下操作:

var ctx = document.getElementById("the-svg"),
textElm = ctx.getElementById("the-text"),
SVGRect = textElm.getBBox();

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("x", SVGRect.x);
    rect.setAttribute("y", SVGRect.y);
    rect.setAttribute("width", SVGRect.width);
    rect.setAttribute("height", SVGRect.height);
    rect.setAttribute("fill", "yellow");
    ctx.insertBefore(rect, textElm);
2020-05-16