複雑な図形

ウェブ機能: マスク SVG

概要

ブラシストロークや有機的なテクスチャなど、複雑な自由形式の形状に要素をクリップするには、CSS マスキング(mask-image)を使用します。clip-path は幾何学的な形状やベクターパスに適していますが、mask-image では、画像(透明度のある PNG など)や SVG を使用して要素の表示領域を定義できます。このアプローチは、半透明をサポートしているため、より表現力に優れています。clip-path では実現が困難または不可能な、ソフトなエッジや複雑なテクスチャを実現できます。

実装

CSS マスクを使用して複雑な図形を実装するには:

画像の透明度を使用する

画像の透明度をマスクとして使用できます。不透明な部分は表示され、透明な部分は非表示になります。これは、PNG、SVG、または透明度のあるその他の画像、または CSS グラデーションなどの生成画像です。

.shaped-element {
  /* MANDATORY: Use vendor prefix for wider support in older browsers */
  -webkit-mask-image: url('mask.svg');
  -webkit-mask-size: cover; /* Scale mask to cover element */
  -webkit-mask-repeat: no-repeat; /* Do not tile the mask */

  /* Standard property for modern browsers */
  mask-image: url('mask.svg');
  mask-size: cover;
  mask-repeat: no-repeat;
}

HTML で SVG 要素を使用する

ページの HTML のインライン SVG で定義された <mask> 要素を参照することもできます。maskContentUnits="objectBoundingBox" を使用すると、要素のサイズに合わせてマスクが自動的にスケーリングされます。これにより、ブラウザはマスク内のすべての座標を絶対ピクセルではなく、0 から 1 までの分数(50% の場合は 0.5 など)として解釈します。

輝度マスクとアルファマスク: デフォルトでは、SVG マスクは輝度(明るさ)を使用して不透明度を決定します。白は表示、黒は非表示、グレーは半透明になります。代わりに SVG シェイプのアルファ チャンネル(透明度)を使用するマスクが必要な場合は、CSS で mask-type: alpha; を指定するか、SVG <mask> 要素で mask-type="alpha" を直接指定します。

<!-- White areas reveal content, gray creates semi-transparency, black or transparent hides it -->
<svg width="0" height="0">
  <defs>
    <!-- objectBoundingBox scales mask coordinates (0 to 1) with the element's size -->
    <mask id="custom-shape" maskContentUnits="objectBoundingBox">
      <!-- Use white shapes to define fully opaque areas -->
      <circle cx="0.5" cy="0.5" r="0.5" fill="white" />
      <!-- Use gray shapes to define semi-transparent/faded areas -->
      <circle cx="0.5" cy="0.5" r="0.25" fill="gray" />
    </mask>
  </defs>
</svg>

<div class="masked-content">
  <!-- Content to be masked -->
</div>

<style>
.masked-content {
  /* Reference the SVG mask ID */
  -webkit-mask-image: url(#custom-shape);
  mask-image: url(#custom-shape);
}
</style>

代替戦略

ブラウザが mask-image または接頭辞付きのバージョンをサポートしていない場合:

  • 要素はクリップされず、通常の長方形として表示されます。
  • マスクがなくてもコンテンツが読みやすく、レイアウトが崩れないようにします(プログレッシブ エンハンスメント)。
  • 必要に応じて、機能検出を使用して、clip-path でよりシンプルな代替シェイプを提供します。
/* Fallback for browsers that do not support masking */
@supports (not (mask-image: url(x))) and (not (-webkit-mask-image: url(x))) {
  .shaped-element {
    /* Use a simple rounded rectangle as fallback */
    clip-path: inset(5% round 15px);
  }
}