javascript - 如何在 d3.js 中的 svg 圆圈内填充图像

标签 javascript d3.js svg

这是我在 svg 中填充圆圈的代码。

   var svgContainer = d3.select("body").append("svg")
                                 .attr("width", 1000)
                             .attr("height", 1000);
    var circles = svgContainer.selectAll("circle")
                      .data(nodes)
                      .enter()
                      .append("circle");

     var circleAttributes = circles
                   .attr("cx", function (d) { return d.x_axis; })
                   .attr("cy", function (d) { return d.y_axis; })
                   .attr("r", function (d) { return d.radius; })
                   .attr('fill', 'green')

但是我不想在我的圈子内填充绿色,而是想在 url 在我的 json 数据中的每个圈子内填充不同的图像。我一直在尝试使用 .attr('fill', url(function(d) {return d.url})) 但它不起作用。我是 d3 的新手,谁能帮我解决这个问题?

最佳答案

从图像创建图案会占用过多内存,并且使用多个图像会造成严重的性能问题。因此,为了避免这种情况,我们可以在图像上使用剪辑路径。

像这样:

var config = {
  "avatar_size": 100
}

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

var defs = svg.append('svg:defs');

data = [{
  posx: 100,
  posy: 100,
  img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/pencil-gear-128.png",
}, {
  posx: 200,
  posy: 200,
  img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/gear-clock-128.png"
}, {
  posx: 300,
  posy: 300,
  img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/magnifier-data-128.png"
}];


svg .append('clipPath')
   .attr('id','clipObj')  
        .append('circle')
         .attr('cx',config.avatar_size/2)
          .attr('cy',config.avatar_size/2)
         .attr('r',config.avatar_size/2);

data.forEach(function(d,i){
  svg.append('image')
     .attr('xlink:href',d.img)
     .attr('width',config.avatar_size)
     .attr('height',config.avatar_size)
 .attr('transform','translate('+parseInt(d.posx+config.avatar_size/2)+','+parseInt(d.posy+config.avatar_size/2)+')')
     .attr('clip-path','url(#clipObj)');
});

我们也可以根据需要轻松地用新的裁剪区域替换裁剪区域。 这是代码笔的链接:http://codepen.io/anon/pen/VagxKp?editors=0010

关于javascript - 如何在 d3.js 中的 svg 圆圈内填充图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100296/

相关文章:

javascript - 如何使用 d3 绘制连续线而不需要单击拖动鼠标,而只是使用 mouseover 事件?

javascript - d3 中的曲线

javascript - 如何在Chrome扩展内容脚本中获取D3节点的数据

html - 如何缩放具有相同位置但位于其他 svg 元素之上的 svg

HTML5/SVG : preserveAspectRatio "none" not working in Firefox

javascript - 如何将新创建的 html 元素绑定(bind)到它的 css

javascript - 使用 AngularJS 从 JSON 访问多个数组

python - 如何将 svg 文件加载到我的 python flask 页面中?

javascript - Google Analytics 跟踪事件不起作用

javascript - 当我添加更多 <script> 标签时会发生什么?