D3 fill shape with image using pattern

后端 未结 1 772
鱼传尺愫
鱼传尺愫 2020-11-29 10:43

I\'m trying to create a circular avatar with D3.js but I cannot get my image to show up in my circle. I\'m using a svg pattern def to attempt to fill the circle with an imag

相关标签:
1条回答
  • 2020-11-29 11:03

    "Fill" is a style property, you have to use CSS url() notation for the reference to the pattern element.

    Once you fix that, you'll discover that you also have your sizes wrong -- unless your intention was to have four copies of the avatar tiled in the circle!

    P.S. I would normally have left this just as a comment, and marked this for closure as a simple typo, but I wanted to try out Stack Snippets:

    var config = {
        "avatar_size" : 48
    }
    
    var body = d3.select("body");
    
    var svg = body.append("svg")
            .attr("width", 500)
            .attr("height", 500);
    
    var defs = svg.append('svg:defs');
    
    defs.append("svg:pattern")
        .attr("id", "grump_avatar")
        .attr("width", config.avatar_size)
        .attr("height", config.avatar_size)
        .attr("patternUnits", "userSpaceOnUse")
        .append("svg:image")
        .attr("xlink:href", 'http://placekitten.com/g/48/48')
        .attr("width", config.avatar_size)
        .attr("height", config.avatar_size)
        .attr("x", 0)
        .attr("y", 0);
    
    var circle = svg.append("circle")
            .attr("cx", config.avatar_size/2)
            .attr("cy", config.avatar_size/2)
            .attr("r", config.avatar_size/2)
            .style("fill", "#fff")
            .style("fill", "url(#grump_avatar)");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

    0 讨论(0)
提交回复
热议问题