【问题标题】:how to use json image as d3.js node background如何使用json图像作为d3.js节点背景
【发布时间】:2015-01-31 00:41:22
【问题描述】:

我对 d3 和 js 很陌生,所以请多多包涵 :) 我正在使用 d3 中的树布局,并且遇到以下问题。

我正在尝试获取我附加在节点上的圆圈以将图像显示为背景图像。我已经看到有关如何通过创建模式然后向其附加图像来做到这一点的相关帖子。

在我的情况下,情况略有不同,因为我需要从 json 对象中提取图像。换句话说,每个节点都应该在我的 json 对象中的“图像”字段下链接相应的图像作为背景图像。我正在使用的 json 对象看起来像

"people": [{
  "name": "John",
  "parent_id": "123",
  "image:http://test.test.com/img2.png"
}, {
  "name": "Paul",
  "parent_id": "687",
  "image:http://test.test.com/img42.png"
} {
  "name": "George",
  "parent_id": "325",
  "image:http://test.test.com/img85.png"
} {
  "name": "Ringo",
  "parent_id": "163",
  "image:http://test.test.com/img93.png"
}]

所以我试图让带有文本附加“Ringo”的节点作为背景图像 img93.png...

希望这是有道理的,在此先感谢大家...

【问题讨论】:

  • @LarsKotthoff,感谢您的及时回复,但我试图让每个节点在数组中显示相应的图像,而不是所有节点上的相同图像..真的找不到建议帖子中的解决方案..我不明白吗?不过谢谢! :D
  • 所以应该是.attr("xlink:href", function(d) { return d.image; })。顺便说一句,您的 JSON 格式似乎是错误的,image 和 : 之后的引号丢失。
  • 感谢您的回复...感谢您注意到引号,幸运的是这是一个示例数组,不是我实际使用的..您的回答对我来说似乎是正确的,但这会返回图像附加到节点,而不是作为附加到节点的“矩形”或“圆形”的背景......你看,我的问题是 json 对象是由其他用户生成的,所以图像有不同的纵横比.. .将它们设置为背景图像可以让我统一它们的大小并保持它们的纵横比。

标签: javascript jquery json d3.js


【解决方案1】:

按照@LarsKotthoff 的回答here 中的建议,将图像定义为图案,然后进行填充。

var data = [{
  "name": "John",
  "parent_id": "123",
  "image": "http://placehold.it/50&text="
}, {
  "name": "Paul",
  "parent_id": "687",
  "image": "http://placehold.it/50&text="
}, {
  "name": "George",
  "parent_id": "325",
  "image": "http://placehold.it/50&text="
}, {
  "name": "Ringo",
  "parent_id": "163",
  "image": "http://placehold.it/50&text="
}];

var svg = d3.select("body")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 150);

svg.append("defs")
  .selectAll("pattern")
  .data(data)
  .enter()
  .append("pattern")
  .attr('id', function(d, i) {
    return d.name;
  })
  .attr('patternUnits', 'userSpaceOnUse')
  .attr('width', 50)
  .attr('height', 50)
  .append("image")
  .attr("xlink:href", function(d) {
    return d.image + d.name;
  })
  .attr('width', 50)
  .attr('height', 50);

var circle = svg.selectAll("circle")
  .data(data)
  .enter().append("circle")
  .attr("cy", 70)
  .attr("cx", function(d, i) {
    return (i + 1) * 100;
  })
  .attr("r", 50)
  .attr("fill", function(d) {
    return "url(#" + d.name + ")";
  });

例如here。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2012-07-16
    • 1970-01-01
    • 2011-11-10
    • 2020-11-14
    • 2021-08-18
    相关资源
    最近更新 更多