【问题标题】:Add Icons next to SVG Text在 SVG 文本旁边添加图标
【发布时间】:2021-02-05 03:59:27
【问题描述】:

我想在 svg 文本旁边添加 2 个图标(附加图像,节点文本/名称将具有差异长度),我知道我们可以使用 foreignObject 但是当使用 foreignObject 时我无法获取节点值

var addSvgCnt = nodeEnter.append("g")
     .attr("class",  "txt-swap-parent");

addSvgCnt.append("foreignObject")
   .attr("width", 1)
   .attr("height", 30)
   .append("xhtml:div")
   .attr("class", "svg-node")
    .html("<img src='https://cdn.onlinewebfonts.com/svg/img_356964.png' height='10' width='10'/>
           <span>BRANCH1.2</span>
           <img src='https://cdn.onlinewebfonts.com/svg/img_356964.png' height='10' width='10'/>");

这里我需要节点文本而不是 BRANCH1.2,我尝试了伪元素,但它也不起作用。实现这一目标的最佳解决方案是什么

【问题讨论】:

  • 您在 SVG 中也有 imagetext
  • 但是当我添加 svg 文本和 svg 图像时,我如何定位这三个元素,如上图所示,节点文本的长度可能不同。 @JavaScript
  • 使用text.textLength

标签: javascript svg d3.js charts


【解决方案1】:

你的图标看起来很像this unicode character,你甚至可以替换它并使用tspan

尝试单击节点以查看单击是否正确注册。

const someText = "Hi from branch 1";
const circledPlusUnicode = "\u2295";
const x = 50, y = 100;

const text = d3.select("svg")
  .append("text")
  .attr("x", x)
  .attr("y", y);

text.append("tspan")
  .attr("class", "circle")
  .text(circledPlusUnicode)
  .on("click", function() {
    console.log("click circle 1");
  });

text.append("tspan")
  .attr("dy", 2)
  .attr("dx", 2)
  .text(someText);

text.append("tspan")
  .attr("class", "circle")
  .attr("dy", -2)
  .attr("dx", 2)
  .text(circledPlusUnicode)
  .on("click", function() {
    console.log("click circle 2");
  });
.circle {
  fill: darkgrey;
  font-size: 14px;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

否则,您使用getBBox,它会返回调用它的元素的边界框,您可以使用它来将图像放在文本旁边:

const someText = "Hi from branch 1";
const circledPlusImg = "https://cdn.onlinewebfonts.com/svg/img_356964.png";
const x = 50,
  y = 100;

const textGroup = d3.select("svg")
  .append("g")
  .attr("transform", "translate" + [x, y] + ")");

textGroup.append("image")
  .attr("class", "circle")
  .attr("href", circledPlusImg)
  .attr("height", 14)
  .attr("width", 14)
  .on("click", function() {
    console.log("click circle 1");
  });

const text = textGroup.append("text")
  .attr("dy", 12)
  .attr("dx", 16)
  .text(someText);

textGroup.append("image")
  .attr("class", "circle")
  .attr("href", circledPlusImg)
  .attr("height", 14)
  .attr("width", 14)
  .attr("x", function() {
    const bbox = text.node().getBBox();
    return bbox.x + bbox.width;
  })
  .on("click", function() {
    console.log("click circle 2");
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2013-10-01
    • 2021-08-14
    • 1970-01-01
    • 2020-02-06
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多