为svg:image设置圆角

mal*_*ouk 9 javascript css svg d3.js

我试图用d3.js为s svg:image(嵌入在SVG中的图像)制作圆角.我无法找到如何正确设置图像样式,因为根据W3C规范,我应该可以使用CSS,但更好的边框和圆角边缘对我有效.

提前致谢.

  vis.append("svg:image")
     .attr("width", width/3)
     .attr("height", height-10)
     .attr("y", 5)
     .attr("x", 5)      
     .attr("style", "border:1px solid black;border-radius: 15px;")
     .attr("xlink:href",
           "http://www.acuteaday.com/blog/wp-content/uploads/2011/03/koala-australia-big.jpg"); 
Run Code Online (Sandbox Code Playgroud)

编辑:

浏览器测试:Firefox,Chrome

Eri*_*röm 26

'border-radius'不适用于svg:image元素(无论如何).解决方法是创建一个带圆角的矩形,并使用剪辑路径.

一个例子.

来源的相关部分:

<defs>
    <rect id="rect" x="25%" y="25%" width="50%" height="50%" rx="15"/>
    <clipPath id="clip">
      <use xlink:href="#rect"/>
    </clipPath>
  </defs>

  <use xlink:href="#rect" stroke-width="2" stroke="black"/>
  <image xlink:href="boston.jpg" width="100%" height="100%" clip-path="url(#clip)"/>
Run Code Online (Sandbox Code Playgroud)

也可以创建几个rect元素而不是使用<use>.


Py.*_*Py. 13

现在还有另一种更干净的方法可以做到这一点。这是使用插入剪辑路径

<image xlink:href="imgUrl" width="100%" height="100%" clip-path="inset(0% round 15px)">
Run Code Online (Sandbox Code Playgroud)

  • 它不适用于我的代码,但 css 可以工作: `image{ Clip-path: inset(0% round 50%); }` (4认同)

小智 6

另一种简单的选择:

将 html<img>标签包裹在<foreignObject>标签中。这允许您使用正常的 html 样式:

<foreignObject x='0' y='0' width='100px' height='100px'>
  <img
    width='100px'
    height='100px'
    src={'path/to/image.png'}
    style={{ borderRadius: '50%' }}
  />
</foreignObject>
Run Code Online (Sandbox Code Playgroud)


Nac*_*oma 5

对于那些只对制作圆形头像感兴趣的人,这里有一个使用 d3 v4 的示例。请注意,您需要在图像处于 (0,0) 时应用剪辑,因此您需要将图像 translate() 到您想要的位置。

import { select } from 'd3-selection';

const AVATAR_WIDTH = 80;
const avatarRadius = AVATAR_WIDTH / 2;
const svg = select('.my-container');
const defs = this.svg.append("defs");
defs.append("clipPath")
  .attr("id", "avatar-clip")
  .append("circle")
  .attr("cx", avatarRadius)
  .attr("cy", avatarRadius)
  .attr("r", avatarRadius)
svg.append("image")
  .attr("x", 0)
  .attr("y", 0)
  .attr("width", AVATAR_WIDTH)
  .attr("height", AVATAR_WIDTH)
  .attr("xlink:href", myAvatarUrl)
  .attr("clip-path", "url(#avatar-clip)")
  .attr("transform", "translate(posx, posy)")
  .append('My username')
Run Code Online (Sandbox Code Playgroud)