【问题标题】:Need to append square image to circular node d3.js需要将方形图像附加到圆形节点d3.js
【发布时间】:2016-03-22 11:45:28
【问题描述】:

您好,我正在尝试将方形图像添加到圆形节点,但将图像裁剪为节点大小。我已成功添加图像,但似乎无法将它们裁剪到圆形节点。关于我做错了什么有什么建议吗?

    var node = svg.selectAll(".node")
      .data(json.nodes)
      .enter().append("g")
      .attr("class", "node")
      .call(force.drag)
      .on('mouseover', connectedNodes)
      .on('mouseout', allNodes)
      .on('contextmenu', function(d){d3.event.preventDefault();tip.show(d);})  //.on('mousedown', tip.show)
    .on('mouseleave', tip.hide);

node.append("circle")
    .attr("r", function(d) { return d.degree;})
    .style("fill", function (d) {return color(d.group);})
    node.append("image")
        .attr("xlink:href",  function(d) { return d.image;})
        .attr("x", function(d) { return -25;})
        .attr("y", function(d) { return -25;})
        .attr("height", 50)
        .attr("width", 50);

如果没有任何图像,我也想在那里显示节点。

【问题讨论】:

  • 你需要使用模式,见herehere

标签: javascript node.js d3.js


【解决方案1】:

使用 svg 剪辑路径。

代码示例:

var nodes = [{
  "id": "0",
  "name": "ETCO I",
  "degree": 50,
  x: 100,
  y: 150

}, {
  "id": "1",
  "name": "PINKERTON Eidel ",  
  "degree": 25,
  x: 200,
  y: 100
}];

var container = d3.select("svg");

var node = container.append("g").selectAll(".node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
  });

node.append("clipPath")
  .attr("id",function(d,i){ return "node_clip"+i })
  .append("circle")
  .attr("r",function(d) {
    return d.degree-2; //-2 to see a small border line
  });


node.append("circle")
  .attr("r", function(d) {
    return d.degree;
  })
  .style("fill", "blue");

node.append("image")
  .attr("xlink:href", function(d) {
    return "https://image.freepik.com/free-icon/group-of-people-in-a-formation_318-44341.png";
  })
  .attr("x",function(d){ return -d.degree })
  .attr("y",function(d){ return -d.degree })
  .attr("height", function(d){ return d.degree*2 })
  .attr("width", function(d){ return d.degree*2 })
  .attr("clip-path",function(d,i){ return "url(#node_clip"+i+")" });
svg {
  background: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width=500 height=200></svg>

【讨论】:

    【解决方案2】:

    我认为这里的第一个答案将帮助您将圆圈设置为图像的蒙版:Setting rounded corners for svg:image。 除此之外,如果您对 SVG 并不是真正的要求,您可以使用普通的 HTML 和 CSS3 来实现图形,并在 &lt;img&gt; 标签上使用旧的 border-radius: 50% 或它们的容器。

    【讨论】:

    • 不幸的是,这对我不起作用,因为我正在使用 node.append("image") .attr("xlink:href", function(d) { return d.图片;})
    猜你喜欢
    • 2017-12-06
    • 1970-01-01
    • 2013-12-21
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多