可以在条形图的条形图中添加图像 - d3js

时间:2013-12-02 10:56:13

标签: javascript angularjs svg d3.js

我试图用d3js和angular创建这个概念: enter image description here

一个重要的方面是我想在栏内添加 封面。经过大量的研究后,我仍然没有想出如何用svg做到这一点。我希望在这里得到一些建议。

这是我认为接近的一段代码,但图像只出现在dom中,并且在条形图顶部不可见:

                  svg.selectAll(".bar")
                      .data(data)
                      .enter().append("rect")
                      .attr("class", "bar")
                      .attr("x", function(d) { return x(d.letter); })
                      .attr("width", x.rangeBand())
                      .attr("y", function(d) { return y(d.frequency); })
                      .attr("height", function(d) { return height - y(d.frequency); })
                        .on('click', function(d, i) {
                          d3.select(this).style("fill", "red");
                           d3.select(this).append("svg:image")
                           .attr("xlink:href", "http://www.e-pint.com/epint.jpg")
                           .attr("width", 50)
                           .attr("height", 70)
                           .attr("x", 0)
                           .attr("y", 0)
                        });

谢谢,

此外,欢迎任何关于此概念和D3执行的其他评论

编辑:

根据第二条评论中发布的问题进行的新试用:

.on('click', function(d, i) {
                          d3.select(this)
                            .append("defs").attr('id', 'aap');

                          svg.select("#aap").append("pattern")
                          .attr('x', '0')
                          .attr('y', '0')
                          .attr("height","200")
                          .attr('width', "200")
                          .attr("id", "cover");

                            svg.select("#cover")
                            .append("svg:image")
                            .attr("xlink:href", "http://www.e-pint.com/epint.jpg")
                            .attr("width", 100)
                            .attr("height", 200)
                            .attr("x", 0)
                            .attr("y", 0)
                        });

不知何故,当我将鼠标悬停在检查器中时,dom中的区域会突出显示为蓝色: enter image description here

1 个答案:

答案 0 :(得分:0)

我在以下代码中完成了它。

http://jsfiddle.net/yduKG/3/

    var svg = d3.select("body").append("svg");

svg
  .append('defs')
  .append('pattern')
    .attr('id', 'diagonalHatch')
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('width', 100)
    .attr('height', 100)
  .append('svg:image')
    .attr("xlink:href", "http://www.e-pint.com/epint.jpg")
        .attr("width", 100)
        .attr("height", 200)
        .attr("x", 0)
        .attr("y", 0);

svg.append("rect")
      .attr("x", 0)
      .attr("width", 100)
      .attr("height", 100)
      .style("fill", 'yellow');

svg.append("rect")
    .attr("x", 0)
    .attr("width", 100)
    .attr("height", 100)
    .style('fill', 'url(#diagonalHatch)');

特别感谢Lars Kotthoff和这个问题:

stackoverflow - fill rect with pattern

相关问题