html clippathを使用して画像を円形に切り抜く

html clippathを使用して画像を円形に切り抜く

htmlで、clipPathタグを使用して画像を円形に切り抜くサンプルを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 84.0.4147.105

円形に切り抜く

clipPathの要素内に、指定したサイズの円の SVGを描写して、
imgタグの「clip-path」に指定します。

<svg width="500" height="500">
  <defs>
    <clipPath id="cli">
      <!-- cx 中心x座標 cy 中心y座標 r 半径 -->
      <circle cx="250" cy="250" r="150" />
    </clipPath>
  </defs>
  <image x="0" y="0" width="500" height="500" xlink:href="sample.jpg" clip-path="url(#cli)" />
</svg>

サンプルコード

以下は、
指定した画像を円形に切り抜く
サンプルコードとなります。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>

<body>
  <div class="main">

    <svg width="500" height="500">
      <defs>
        <clipPath id="cli">
          <!-- cx 中心x座標 cy 中心y座標 r 半径 -->
          <circle cx="250" cy="250" r="150" />
        </clipPath>
      </defs>
      <image x="0" y="0" width="500" height="500"
        xlink:href="https://images.unsplash.com/photo-1602214384586-2f6575d74366?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80"
        clip-path="url(#cli)" />
    </svg>

  </div>
</body>

</html>

画像が切り抜かれていることが確認できます。