SVG - How to crop an image to a circle?

前端 未结 2 1345
说谎
说谎 2020-12-15 17:36

I am somewhat of a noob to SVG, but I\'ve been playing with D3 and have started to undestand the basics.

What I am trying to achieve is to take a square image and cr

相关标签:
2条回答
  • 2020-12-15 17:52

    You can use a clip path, like so:

    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
      <clipPath id="clipCircle">
        <circle r="50" cx="50" cy="50"/>
      </clipPath>
      <rect width="100" height="100" clip-path="url(#clipCircle)"/>
    </svg>
    

    A circle will be "cut out" from the rectangle.

    0 讨论(0)
  • 2020-12-15 18:07

    If you want to generate the same html code as in @Thomas's answer programmatically with D3 you can do the following:

    var svg = d3.select("body").append("svg")
      .attr("width", "100%")
      .attr("height", "100%");
    
    svg.append("clipPath")
        .attr("id", "clipCircle")
      .append("circle")
        .attr("r", 50)
        .attr("cx", 50)
        .attr("cy", 50);
    
    svg.append("rect")
        .attr("width", 100)
        .attr("height", 100)
        .attr("clip-path", "url(#clipCircle)");
    
    0 讨论(0)
提交回复
热议问题