D3使用图案填充图像 [英] D3 fill shape with image using pattern

查看:474
本文介绍了D3使用图案填充图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用D3.js创建一个圆形头像,但我无法让我的图片显示在我的圈子中。我使用一个svg模式def试图填充一个图像。

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


推荐答案

Fill是一个样式属性,使用CSS url()符号来引用模式元素。

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

PS我通常会留下这只是一个评论,并标记这封闭作为一个简单的错字,但我想试试 Stack Snippets

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>

这篇关于D3使用图案填充图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆