javascript - 将图像添加到 D3.js Sunburst 示例

标签 javascript svg d3.js sunburst-diagram

我想扩展这个 D3.js sunburst 示例,让它可以显示图像而不是文本。 http://www.jasondavies.com/coffee-wheel/

enter image description here

js示例代码中有趣的部分如下:

d3.json("wheel.json", function(error, json) {
  var nodes = partition.nodes({children: json});

  var path = vis.selectAll("path").data(nodes);
  path.enter().append("path")
      .attr("id", function(d, i) { return "path-" + i; })
      .attr("d", arc)
      .attr("fill-rule", "evenodd")
      .style("fill", colour)
      .on("click", click);

  var text = vis.selectAll("text").data(nodes);
  var textEnter = text.enter().append("text")
      .style("fill-opacity", 1)
      .style("fill", function(d) {
        return brightness(d3.rgb(colour(d))) < 125 ? "#eee" : "#000";
      })
      .attr("text-anchor", function(d) {
        return x(d.x + d.dx / 2) > Math.PI ? "end" : "start";
      })
      .attr("dy", ".2em")
      .attr("transform", function(d) {
        var multiline = (d.name || "").split(" ").length > 1,
            angle = x(d.x + d.dx / 2) * 180 / Math.PI - 90,
            rotate = angle + (multiline ? -.5 : 0);
        return "rotate(" + rotate + ")translate(" + (y(d.y) + padding) + ")rotate(" + (angle > 90 ? -180 : 0) + ")";
      })
      .on("click", click);
  textEnter.append("tspan")
      .attr("x", 0)
      .text(function(d) { return d.depth ? d.name.split(" ")[0] : ""; });
  textEnter.append("tspan")
      .attr("x", 0)
      .attr("dy", "1em")
      .text(function(d) { return d.depth ? d.name.split(" ")[1] || "" : ""; });

问题是在这种情况下如何用图像替换文本。

非常感谢。

最佳答案

var image = vis.selectAll("image").data(nodes);
var imageEnter = image.enter().append("image")
  .attr("xlink:href", "https://github.com/favicon.ico")
  .attr("width", 16)
  .attr("height", 16)
  .attr("x", function (d) { 
    return 33; // calculate x 
  }).attr("y", function (d) {
    return 33; // calculate y 
  });

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image

强制引导图像和标签:http://bl.ocks.org/mbostock/950642

关于javascript - 将图像添加到 D3.js Sunburst 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20069729/

相关文章:

javascript - 将空间渲染为 div 文本元素中的唯一字符

javascript - 将 SVG 条纹图案转换为 d3

javascript - JQuery移动 ListView 过滤器初始化

javascript - 向下滚动时更早触发一个类

javascript - 来自 subview 的 Backbone.JS 自定义事件

css - 链接到片段时,父 SVG 默认为 150x300 - 如何修复?

jquery - 如何使用 CSS(jQuery SVG 图像替换)更改 SVG 图像的颜色?

javascript - d3 js输入方法不起作用

javascript - 找到位于 ARC 的起始 Angular 和结束 Angular 之间的点。

javascript - 从可变长度字符串中提取 lat、lng