탐색

v2.1.0
미디어

이미지 비교

같은 대상을 담은 두 이미지와 그 사이의 경계선을 움직이는 손잡이입니다.

이 페이지의 내용

이미지 비교 컴포넌트는 같은 대상을 담은 두 이미지를 겹쳐 보여 주고, 사용자가 두 이미지 사이의 경계선을 움직일 수 있게 합니다. 편집 전후, 밝은 버전과 어두운 버전, 초안과 수정본 등을 비교할 수 있습니다. 조작부는 네이티브 <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를 설정해 프레임의 형태를 정하고, 구도가 같은 두 이미지를 사용하세요.

프레임에는 표면과 같은 모서리 처리와 모든 그림에 적용되는 안쪽 테두리가 있습니다. 카드 안에 배치할 때는 --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 입력과 같은 방식으로 선을 한 단계 옮깁니다.
Home, End이미지 한 장 전체 표시

#접근성

  • 입력 요소의 접근 가능한 이름에는 손잡이를 움직였을 때의 효과를 담으세요. 예를 들어 "색을 보정한 이미지 더 많이 보기"로 지정할 수 있습니다.
  • 각 이미지의 alt 속성에는 어느 버전인지와 다른 이미지와의 차이를 설명하세요. 두 이미지를 나란히 볼 수 없는 사용자도 설명을 읽고 차이를 알 수 있어야 합니다.
  • Tab 키로 이동할 때 손잡이는 하나의 포커스 지점입니다. 방향키를 누르면 경계선이 한 단계씩 이동하고, Home과 End를 누르면 각각 한쪽 이미지 전체가 표시됩니다.
  • 손잡이 크기는 포인터 종류와 관계없이 32px이며, 터치 화면에서는 손잡이를 둘러싼 조작 영역의 높이가 44px입니다. 프레임 위에서도 손가락을 위아래로 움직여 페이지를 스크롤할 수 있습니다.

#React, Svelte 및 Vue

compare 컴포넌트는 동작을 연결하고 위치 값을 주고받습니다. 두 이미지는 페이지의 마크업에 직접 작성합니다. 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프레임은 두 이미지를 겹쳐 배치하고 구분선을 그리며 표면의 모서리 반경을 적용합니다.
compare-before아래에 깔린 이미지는 시작점부터 경계선까지 표시합니다
compare-after위에 겹친 이미지는 경계선에서 잘라 경계선부터 끝까지 표시합니다
compare-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%;  }}