Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

javascript - D3 fill shape with image using pattern

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 image.

Can anyone tell me what I'm doing wrong below? Thank you.

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", 'images/avatars/avatar_grumpy.png')
    .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)
        .attr("cy", config.avatar_size)
        .attr("r", config.avatar_size)
        .style("fill", "#fff")
        .style("fill", "#grump_avatar");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...