簡體   English   中英

為 svg:image 設置圓角

[英]Setting rounded corners for svg:image

我試圖用 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 元素(無論如何)。 一種解決方法是創建一個帶圓角的矩形,並使用剪輯路徑。

一個例子

源碼的相關部分:

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

對於那些只對制作圓形頭像感興趣的人,這里有一個使用 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')

另一個簡單的選擇:

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

現在還有另一種方法可以做到這一點,它有點干凈。 它是使用插入的 clip-path

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM