ナビゲーション

v2.1.0
メディア

画像比較

同じ対象を写した 2 枚の画像を、境界線のハンドルを動かして比較できます。

このページの内容

画像比較では、同じ対象の 2 枚の画像を重ね、境界線を動かして編集前後、ライト表示とダーク表示、初稿と改訂版などを見比べられます。ハンドルにはネイティブの <input type="range"> を使い、スライダー標準のキー操作、値、名前を利用できます。細い境界線には真珠のような質感のつまみが付き、手前の画像はその線に沿って切り抜かれます。

画像比較

<figure class="compare max-w(520) mx-auto">  <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">  <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">  <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture"></figure><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLElement>(null)  useEffect(() => attach(root.current!), [])  return (    <figure ref={root} className="compare max-w(520) mx-auto">      <img className="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style={{ aspectRatio: '16 / 10', filter: 'grayscale(1) contrast(.75)' }} />      <img className="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading" />      <input type="range" className="compare-range" min="0" max="100" defaultValue="50" aria-label="Show more of the graded picture" />    </figure>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><figure class="compare max-w(520) mx-auto" {@attach attach}>  <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">  <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">  <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture"></figure>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <figure ref="root" class="compare max-w(520) mx-auto">    <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">    <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">    <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture">  </figure></template>
つまみをドラッグするか、つまみにフォーカスして矢印キーを押します。

#ハンドルと画像表示の連動

スクロール駆動アニメーションに対応したブラウザーでは、入力要素内のつまみを基準にしたビュータイムラインをフレームが参照します。スクリプトなしで --compare-position がつまみの位置に追従し、画像の切り抜きと境界線はそのプロパティに連動します。

非対応のブラウザーでは、compare ビヘイビアが同じ処理を行います。適用時と入力値が変わるたびに、入力値が範囲内のどの位置にあるかを百分率に換算し、ルート要素の --compare-position に書き込みます。ビヘイビアはすべてのブラウザーで適用してください。スタイルシートがすでにプロパティを制御している場合、スクリプトは表示に影響しません。

app.js
import { compare } from '@master/ui/behaviors/compare.js'const detach = compare(document.querySelector('.compare'))

ビヘイビアは compare クラスを持つルート要素を受け取ります。オプションや独自のイベントはありません。範囲入力は標準の input と change を発行し、その value が境界線の位置を示します。スタイルシートのタイムラインが機能せず、ビヘイビアも適用していない場合、境界線は --compare-position で指定した位置に固定されます。既定は中央です。

入力要素はフレームよりつまみ一つ分だけ幅が広くなっています。つまみの中心がフレームの端から端まで移動できるため、境界線をどちらの端にも合わせられます。

#画像

compare-before は背面にあり、始端から境界線までが表示されます。compare-after は前面にあり、境界線から終端までが表示されます。どちらの画像もフレーム全体を覆い、フレームの形に合わせて切り抜かれます。一方の画像に幅と高さ、または aspect-ratio を指定してフレームの形を決め、同じ構図の画像を 2 枚使ってください。

フレームにはサーフェスと同じ角の丸みと、すべての 図版 に共通する内側の輪郭が付きます。カードの中に配置する場合は --compare-radius を指定します。

カード内での表示

<div class="card w(280)">  <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">    <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">    <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">    <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">  </figure>  <div class="card-header">    <h3 class="card-title">Warm</h3>    <p class="card-description">Drag to compare with the original.</p>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="card w(280)">      <figure className="compare card-media" style={{ '--compare-radius': 'calc(var(--radius-surface) - 4px)' } as React.CSSProperties}>        <img className="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style={{ aspectRatio: '4 / 3', filter: 'saturate(.2) brightness(.92)' }} />        <img className="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset" />        <input type="range" className="compare-range" min="0" max="100" defaultValue="40" aria-label="Show more of the Warm preset" />      </figure>      <div className="card-header">        <h3 className="card-title">Warm</h3>        <p className="card-description">Drag to compare with the original.</p>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="card w(280)" {@attach attach}>  <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">    <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">    <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">    <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">  </figure>  <div class="card-header">    <h3 class="card-title">Warm</h3>    <p class="card-description">Drag to compare with the original.</p>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="card w(280)">    <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">      <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">      <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">      <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">    </figure>    <div class="card-header">      <h3 class="card-title">Warm</h3>      <p class="card-description">Drag to compare with the original.</p>    </div>  </div></template>

#キーボード操作

範囲入力の標準キー操作を使います。ビヘイビアによる追加のキー操作はありません。

キー操作
ArrowLeft, ArrowRight, ArrowUp, ArrowDownネイティブのrange入力と同様に、線を1ステップ移動
Home, End画像1枚の全体を表示

#アクセシビリティ

  • 「色調補正後の画像の表示範囲を広げる」のように、操作すると何が変わるかがわかる名前を入力要素に付けます。
  • 各画像に alt を付け、どちらの画像か、もう一方とどう違うかを記述します。2 枚を見比べられない読者にも、違いが言葉で伝わるようにします。
  • ハンドルは、Tab キーで移動できる一つのフォーカス先です。矢印キーで境界線を 1 ステップずつ動かせます。Home と End では、それぞれ片方の画像が全体表示されます。
  • つまみのサイズはどのポインターでも 32px です。タッチ画面では、つまみを囲むハンドルの高さが 44px になります。フレーム上で指を上下に動かして、ページを縦にスクロールできます。

#React、Svelte、Vue

compare コンポーネントはビヘイビアを適用し、境界線の位置を受け渡します。2 枚の画像はページ側のマークアップに記述します。npx master-ui add compare でプロジェクトにコピーできます。コンポーネントの構成と使い方は React、Svelte、Vue を参照してください。

ui/compare.tsx
'use client'import { useState, type ComponentProps } from 'react'import { compare } from '@master/ui/behaviors/compare.js'import { useBehavior } from './use-behavior'export interface CompareProps extends Omit<ComponentProps<'figure'>, 'defaultValue' | 'ref'> {  /** How much of the second picture shows, from 0 to 100. */  value?: number  defaultValue?: number  onValueChange?: (value: number) => void  /** The name of the handle: what moving it shows. */  label: string}/** Two pictures and the line between them. The children are the two images, `compare-before` and `compare-after`. */export function Compare({ value, defaultValue = 50, onValueChange, label, className, children, ...root }: CompareProps) {  const ref = useBehavior(compare, undefined, { value, defaultValue, onValueChange })  const [first] = useState(value ?? defaultValue)  return (    <figure className={className ? `compare ${className}` : 'compare'} ref={ref} {...root}>      {children}      <input type="range" className="compare-range" min={0} max={100} defaultValue={first} aria-label={label} />    </figure>  )}
ui/Compare.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  export interface CompareProps extends HTMLAttributes<HTMLElement> {    /** How much of the second picture shows, from 0 to 100. Bind it, or leave it out: it starts at 50. */    value?: number    onValueChange?: (value: number) => void    /** The name of the handle: what moving it shows. */    label: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { compare } from '@master/ui/behaviors/compare.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, label, class: className, children, ...root }: CompareProps = $props()  const first = untrack(() => value) ?? 50  const attach = behavior(compare, undefined, {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  Two pictures and the line between them. The children are the two images, `compare-before` and `compare-after`.--><figure class={['compare', className]} {@attach attach} {...root}>  {@render children?.()}  <input type="range" class="compare-range" min="0" max="100" value={first} aria-label={label} /></figure>
ui/Compare.vue
<script setup lang="ts">import { useTemplateRef } from 'vue'import { compare } from '@master/ui/behaviors/compare.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })defineProps<{  /** The name of the handle: what moving it shows. */  label: string}>()/** How much of the second picture shows, from 0 to 100: `v-model`. */const model = defineModel<number>({ default: 50 })/* Two pictures and the line between them. The default slot is the two images, `compare-before` and `compare-after`. */const first = model.valueconst root = useTemplateRef<HTMLElement>('root')useBehavior(root, compare, undefined, model)</script><template>  <figure class="compare" ref="root" v-bind="$attrs">    <slot />    <input type="range" class="compare-range" min="0" max="100" :value.attr="first" :aria-label="label">  </figure></template>

#クラス

クラス説明
compareフレームは 2 枚の画像を重ね、境界線を描画し、サーフェスの角丸を適用します。
compare-before下に重ねる画像。始端から境界線までを表示します。
compare-after上に重ねる画像。境界線で切り抜き、境界線から終端までを表示します。
compare-rangeハンドルはフレーム全体にわたる range 入力です。トラックは表示せず、グリップをつまみとして使います。動かしたときに何が変わるかを表す名前を付けます。

#カスタムプロパティ

プロパティ既定値説明
--compare-position始端からの線の位置をパーセントで指定。初期値50%で登録され、スタイルシートまたはスクリプトがハンドルの位置に応じて設定する
--compare-radiusvar(--radius-surface)フレームの角の丸み。カード内に収める場合は値を小さくする
--compare-grip2remグリップのサイズ。精度の低いポインターでは、グリップを囲むハンドルの高さが 2.75rem 以上になります

#ソース

@master/ui/components/compare.css
/* * Compare: two pictures of the same thing, one over the other, and a handle that draws the line between them. * The handle is a native range input: it has the keys, the value and the name of a slider. Its thumb is a * pearl grip on a fine line; the picture on top is clipped at the line. * Where scroll-driven animations exist the thumb's own place in the input sets --compare-position, so the * picture follows the handle with no script. Elsewhere a script copies the input's value into the same * property, and without either the pictures stay parted where --compare-position puts them. * The input is one grip wider than the frame, so the middle of the grip runs from one edge to the other. */@property --compare-position {  syntax: '<percentage>';  inherits: true;  initial-value: 50%;}@layer components.ui {  .compare {    --compare-radius: var(--radius-surface);    --compare-grip: 2rem;    position: relative;    display: grid;    min-width: 0;    margin: 0;    border-radius: calc(var(--compare-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: clip;    background: var(--color-surface-chip);    user-select: none;    -webkit-user-select: none;    isolation: isolate;    /* The line between the two pictures: pearl, with a faint dark edge so it holds on a pale picture. */    &::before {      content: '';      position: absolute;      inset-block: 0;      inset-inline-start: var(--compare-position);      z-index: 1;      width: 1.5px;      translate: -50% 0;      background: var(--color-on-image);      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 0 6px var(--color-on-image-shade);      pointer-events: none;    }    &:dir(rtl)::before {      translate: 50% 0;    }    /* The inward edge every picture gets, drawn over both of them. */    &::after {      content: '';      position: absolute;      inset: 0;      z-index: 2;      border-radius: inherit;      corner-shape: inherit;      box-shadow: inset 0 0 0 1px var(--color-line-image);      pointer-events: none;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;      &::before {        background: CanvasText;      }    }  }  /* The two pictures share one cell and one size. */  .compare-before, .compare-after {    display: block;    grid-area: 1 / 1;    width: 100%;    height: 100%;    max-width: none;    margin: 0;    object-fit: cover;    pointer-events: none;  }  /* The one on top shows from the line to the end. */  .compare-after {    clip-path: inset(0 0 0 var(--compare-position));    &:dir(rtl) {      clip-path: inset(0 var(--compare-position) 0 0);    }  }  /* The handle: a range input across the middle of the frame, with no track and a grip for a thumb. */  .compare-range {    position: absolute;    inset-block-start: 50%;    inset-inline: calc(var(--compare-grip) / -2);    z-index: 3;    width: calc(100% + var(--compare-grip));    /*     * 4px taller than the grip above and below, where its track stays centered: the focus ring stands 4px outside     * the grip, and the input clips what it holds where it is the grip's view timeline.     */    height: calc(var(--compare-grip) + .5rem);    margin: 0;    padding: 0;    border: 0;    translate: 0 -50%;    background: transparent;    appearance: none;    cursor: ew-resize;    touch-action: pan-y;    -webkit-tap-highlight-color: transparent;    &:focus-visible {      outline: none;    }    &::-webkit-slider-runnable-track {      height: var(--compare-grip);      background: transparent;    }    /* The grip: the pearl thumb of a slider, larger, with a pair of chevrons to say which way it goes. */    &::-webkit-slider-thumb {      width: var(--compare-grip);      height: var(--compare-grip);      border: 0;      border-radius: 999px;      background:        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='none' stroke='%2334353a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m13 12-4 4 4 4M19 12l4 4-4 4'/%3E%3C/svg%3E") center / contain no-repeat,        linear-gradient(180deg, var(--color-thumb-high), var(--color-thumb-low));      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade), 0 8px 16px -8px var(--color-on-image-shade);      appearance: none;      transition: scale var(--duration-quick) var(--easing-glide);    }    &::-moz-range-track {      height: var(--compare-grip);      background: transparent;    }    &::-moz-range-thumb {      width: var(--compare-grip);      height: var(--compare-grip);      border: 0;      border-radius: 999px;      background:        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='none' stroke='%2334353a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m13 12-4 4 4 4M19 12l4 4-4 4'/%3E%3C/svg%3E") center / contain no-repeat,        linear-gradient(180deg, var(--color-thumb-high), var(--color-thumb-low));      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade), 0 8px 16px -8px var(--color-on-image-shade);      transition: scale var(--duration-quick) var(--easing-glide);    }    /* Held, the grip swells a little; a disabled handle is not held and does not answer. */    &:active:not(:disabled)::-webkit-slider-thumb {      scale: 1.06;    }    &:active:not(:disabled)::-moz-range-thumb {      scale: 1.06;    }    &:disabled {      cursor: default;    }    &:focus-visible::-webkit-slider-thumb {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: 0 0 0 2px var(--color-focus), 0 0 0 .5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade);    }    &:focus-visible::-moz-range-thumb {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: 0 0 0 2px var(--color-focus), 0 0 0 .5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade);    }    /* On touch the input reaches 44px tall around the grip, which keeps its size; a finger anywhere on it moves the line. */    @media (pointer: coarse) {      height: max(var(--compare-grip) + .5rem, 2.75rem);    }    @media (prefers-reduced-motion: reduce) {      &:active:not(:disabled)::-webkit-slider-thumb {        scale: none;      }      &:active:not(:disabled)::-moz-range-thumb {        scale: none;      }    }    @media (forced-colors: active) {      &::-webkit-slider-thumb {        forced-color-adjust: none;        background: ButtonText;        box-shadow: none;      }      /* A selector list with an unknown vendor pseudo-element is dropped whole, so each engine has its own rule. */      &::-moz-range-thumb {        forced-color-adjust: none;        background: ButtonText;        box-shadow: none;      }      &:focus-visible::-webkit-slider-thumb {        outline-color: Highlight;      }      &:focus-visible::-moz-range-thumb {        outline-color: Highlight;      }    }  }  /* The handle moves the picture: the grip is a view timeline in its input and the frame reads it. */  @supports (view-timeline: --compare-grip inline) and (timeline-scope: --compare-grip) {    .compare {      timeline-scope: --compare-grip;      animation-name: compare-position;      animation-timing-function: linear;      animation-fill-mode: both;      animation-timeline: --compare-grip;      animation-range: contain;      &:dir(rtl) {        animation-direction: reverse;      }    }    .compare-range {      overflow: hidden;      &::-webkit-slider-thumb {        view-timeline: --compare-grip inline;      }    }  }}@keyframes compare-position {  from {    --compare-position: 100%;  }  to {    --compare-position: 0%;  }}