html feColorMatrixタグを使用して画像をモノクロ表示にする

html feColorMatrixタグを使用して画像をモノクロ表示にする

htmlで、feColorMatrixタグを使用して、画像をモノクロ表示にするサンプルを記述してます。

環境

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

feColorMatrixタグ使い方

filterの要素内に、feColorMatrixタグを使用して、彩度を 0 にするフィルターを作成して、imgタグの「filter」に指定します。

<svg width="500" height="500">
  <defs>
    <filter id="mono">
      <feColorMatrix type="saturate" values="0" />
    </filter>
  </defs>
  <image x="0" y="0" width="500" height="500" xlink:href="https://pro-foto.jp/free/img/images_big/eha0171-009.jpg"
    filter="url(#mono)" />
</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>
        <filter id="mono">
          <feColorMatrix type="saturate" values="0" />
        </filter>
      </defs>
      <image x="0" y="0" width="500" height="500" xlink:href="https://pro-foto.jp/free/img/images_big/eha0171-009.jpg"
        filter="url(#mono)" />
    </svg>

  </div>
</body>

</html>

画像がモノクロ表示されていることが確認できます。

CSSを使用すると、マウスオーバーで元に色に戻すことが可能です。

<!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;
  }
  svg image {
    filter: url(#mono);
  }
  svg image:hover {
    filter: none;
  }
</style>

<body>
  <div class="main">

    <svg width="500" height="500">
      <defs>
        <filter id="mono">
          <feColorMatrix type="saturate" values="0" />
        </filter>
      </defs>
      <image x="0" y="0" width="500" height="500" xlink:href="https://pro-foto.jp/free/img/images_big/eha0171-009.jpg"
        filter="url(#mono)" />
    </svg>

  </div>
</body>

</html>

マウスオーバーすると画像の「filter」がなくなり、カラーに戻っていることが確認できます。

以下のようにして、色相を変換したりすることも可能です。

<feColorMatrix type="hueRotate" values="90" />