为svg:image设置圆角

Setting rounded corners for svg:image

本文关键字:设置 圆角 image svg      更新时间:2023-09-26

我试图用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"); 
编辑:

测试浏览器:Firefox, Chrome

'border-radius'不适用于svg:image元素(无论如何)。一个解决方法是创建一个圆角矩形,并使用clip-path。

一个例子。

来源的相关部分:

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

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

现在有另一种更简洁的方法。这是为了使用插入的剪辑路径。

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

另一个简单的选择:

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

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

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')