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

查看:42
本文介绍了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!

附言我通常会把它作为评论留下,并将其标记为一个简单的错字,但我想尝试一下 堆栈代码段:

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天全站免登陆