이미지 비교 컴포넌트는 같은 대상을 담은 두 이미지를 겹쳐 보여 주고, 사용자가 두 이미지 사이의 경계선을 움직일 수 있게 합니다. 편집 전후, 밝은 버전과 어두운 버전, 초안과 수정본 등을 비교할 수 있습니다. 조작부는 네이티브 <input type="range">이므로 슬라이더의 키보드 조작, 값, 접근 가능한 이름을 지원합니다. 가는 경계선 위에는 진주처럼 둥근 손잡이가 있고, 위에 놓인 이미지는 이 경계선을 기준으로 잘립니다.
이미지 비교
<figureclass="compare max-w(520)mx-auto"><imgclass="compare-before"src="/demo/moonstone.svg"alt="The landscape before grading: grey and flat"style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)"><imgclass="compare-after"src="/demo/moonstone.svg"alt="The landscape after grading"><inputtype="range"class="compare-range"min="0"max="100"value="50"aria-label="Show more of the graded picture"></figure><scripttype="module">import{ attach }from'@master/ui/behaviors'attach()</script>
import{ useEffect, useRef }from'react'import{ attach }from'@master/ui/behaviors'exportfunctionExample(){const root =useRef<HTMLElement>(null)useEffect(()=>attach(root.current!),[])return(<figureref={root}className="compare max-w(520)mx-auto"><imgclassName="compare-before"src="/demo/moonstone.svg"alt="The landscape before grading: grey and flat"style={{aspectRatio:'16 / 10',filter:'grayscale(1) contrast(.75)'}}/><imgclassName="compare-after"src="/demo/moonstone.svg"alt="The landscape after grading"/><inputtype="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><figureclass="compare max-w(520)mx-auto"{@attach attach}><imgclass="compare-before"src="/demo/moonstone.svg"alt="The landscape before grading: grey and flat"style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)"><imgclass="compare-after"src="/demo/moonstone.svg"alt="The landscape after grading"><inputtype="range"class="compare-range"min="0"max="100"value="50"aria-label="Show more of the graded picture"></figure>
<scriptsetup>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><figureref="root"class="compare max-w(520)mx-auto"><imgclass="compare-before"src="/demo/moonstone.svg"alt="The landscape before grading: grey and flat"style="aspect-ratio:16/10;filter:grayscale(1)contrast(.75)"><imgclass="compare-after"src="/demo/moonstone.svg"alt="The landscape after grading"><inputtype="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에 복사합니다. 모든 브라우저에서 이 동작을 연결하세요. 스타일시트가 이미 이 속성을 제어하는 브라우저에서는 스크립트가 화면 표시에 영향을 주지 않습니다.
이 동작은 compare 클래스가 적용된 루트 요소를 받습니다. 자체 옵션과 이벤트는 없으며, 입력 요소는 일반 범위 입력과 마찬가지로 input과 change 이벤트를 발생시키며, 입력 요소의 value가 경계선의 위치를 결정합니다. 스타일시트의 타임라인과 이 동작이 모두 없으면 두 이미지는 --compare-position에 지정된 위치에서 나뉜 상태로 유지됩니다. 별도로 설정하지 않으면 경계선은 중앙에 놓입니다.
입력 요소는 프레임보다 손잡이 너비만큼 넓습니다. 따라서 손잡이 중심이 프레임의 한쪽 끝에서 다른 쪽 끝까지 움직일 수 있고, 경계선도 양쪽 끝에 닿을 수 있습니다.
compare-before 이미지는 아래에 놓이며 시작점부터 경계선까지 보입니다. compare-after 이미지는 위에 놓이며 경계선부터 끝점까지 보입니다. 두 이미지 모두 프레임을 채우고 프레임 밖은 잘립니다. 한 이미지에 너비와 높이를 지정하거나 aspect-ratio를 설정해 프레임의 형태를 정하고, 구도가 같은 두 이미지를 사용하세요.
프레임에는 표면과 같은 모서리 처리와 모든 그림에 적용되는 안쪽 테두리가 있습니다. 카드 안에 배치할 때는 --compare-radius를 설정하세요.
카드 안의 이미지 비교
<divclass="card w(280)"><figureclass="compare card-media"style="--compare-radius: calc(var(--radius-surface) - 4px)"><imgclass="compare-before"src="/demo/portrait-1.svg"alt="The portrait as uploaded"style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)"><imgclass="compare-after"src="/demo/portrait-1.svg"alt="The portrait with the Warm preset"><inputtype="range"class="compare-range"min="0"max="100"value="40"aria-label="Show more of the Warm preset"></figure><divclass="card-header"><h3class="card-title">Warm</h3><pclass="card-description">Drag to compare with the original.</p></div></div><scripttype="module">import{ attach }from'@master/ui/behaviors'attach()</script>
import{ useEffect, useRef }from'react'import{ attach }from'@master/ui/behaviors'exportfunctionExample(){const root =useRef<HTMLDivElement>(null)useEffect(()=>attach(root.current!),[])return(<divref={root}className="card w(280)"><figureclassName="compare card-media"style={{'--compare-radius':'calc(var(--radius-surface) - 4px)'}asReact.CSSProperties}><imgclassName="compare-before"src="/demo/portrait-1.svg"alt="The portrait as uploaded"style={{aspectRatio:'4 / 3',filter:'saturate(.2) brightness(.92)'}}/><imgclassName="compare-after"src="/demo/portrait-1.svg"alt="The portrait with the Warm preset"/><inputtype="range"className="compare-range"min="0"max="100"defaultValue="40"aria-label="Show more of the Warm preset"/></figure><divclassName="card-header"><h3className="card-title">Warm</h3><pclassName="card-description">Drag to compare with the original.</p></div></div>)}
<script>import{ attach }from'@master/ui/behaviors'</script><divclass="card w(280)"{@attach attach}><figureclass="compare card-media"style="--compare-radius: calc(var(--radius-surface) - 4px)"><imgclass="compare-before"src="/demo/portrait-1.svg"alt="The portrait as uploaded"style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)"><imgclass="compare-after"src="/demo/portrait-1.svg"alt="The portrait with the Warm preset"><inputtype="range"class="compare-range"min="0"max="100"value="40"aria-label="Show more of the Warm preset"></figure><divclass="card-header"><h3class="card-title">Warm</h3><pclass="card-description">Drag to compare with the original.</p></div></div>
<scriptsetup>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><divref="root"class="card w(280)"><figureclass="compare card-media"style="--compare-radius:calc(var(--radius-surface)-4px)"><imgclass="compare-before"src="/demo/portrait-1.svg"alt="The portrait as uploaded"style="aspect-ratio:4/3;filter:saturate(.2)brightness(.92)"><imgclass="compare-after"src="/demo/portrait-1.svg"alt="The portrait with the Warm preset"><inputtype="range"class="compare-range"min="0"max="100"value="40"aria-label="Show more of the Warm preset"></figure><divclass="card-header"><h3class="card-title">Warm</h3><pclass="card-description">Drag to compare with the original.</p></div></div></template>
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'exportinterfaceComparePropsextendsOmit<ComponentProps<'figure'>,'defaultValue'|'ref'>{/** How much of the second picture shows, from 0 to 100. */value?:numberdefaultValue?:numberonValueChange?:(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`. */exportfunctionCompare({ value, defaultValue =50, onValueChange, label, className, children,...root }:CompareProps){const ref =useBehavior(compare,undefined,{ value, defaultValue, onValueChange })const[first]=useState(value ?? defaultValue)return(<figureclassName={className ?`compare ${className}`:'compare'}ref={ref}{...root}>{children}<inputtype="range"className="compare-range"min={0}max={100}defaultValue={first}aria-label={label}/></figure>)}
ui/Compare.svelte
<scriptlang="ts"module>importtype{ HTMLAttributes }from'svelte/elements'exportinterfaceComparePropsextendsHTMLAttributes<HTMLElement>{/** How much of the second picture shows, from 0 to 100. Bind it, or leave it out: it starts at 50. */value?:numberonValueChange?:(value:number)=>void/** The name of the handle: what moving it shows. */label:string}</script><scriptlang="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)??50const 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`.--><figureclass={['compare', className]}{@attach attach}{...root}>{@renderchildren?.()}<inputtype="range"class="compare-range"min="0"max="100"value={first}aria-label={label}/></figure>
ui/Compare.vue
<scriptsetuplang="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><figureclass="compare"ref="root"v-bind="$attrs"><slot /><inputtype="range"class="compare-range"min="0"max="100":value.attr="first":aria-label="label"></figure></template>
/* * 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:000.5pxvar(--color-on-image-shade),006pxvar(--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:inset0001pxvar(--color-line-image);pointer-events:none;}@media(forced-colors:active){outline:1pxsolid 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(000var(--compare-position));&:dir(rtl){clip-path:inset(0var(--compare-position)00);}}/* 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/containno-repeat,linear-gradient(180deg,var(--color-thumb-high),var(--color-thumb-low));box-shadow:000.5pxvar(--color-on-image-shade),01px2px-.5pxvar(--color-on-image-shade),03px6px-2pxvar(--color-on-image-shade),08px16px-8pxvar(--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/containno-repeat,linear-gradient(180deg,var(--color-thumb-high),var(--color-thumb-low));box-shadow:000.5pxvar(--color-on-image-shade),01px2px-.5pxvar(--color-on-image-shade),03px6px-2pxvar(--color-on-image-shade),08px16px-8pxvar(--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:2pxsolidvar(--color-on-image);outline-offset:2px;box-shadow:0002pxvar(--color-focus),000.5pxvar(--color-on-image-shade),03px6px-2pxvar(--color-on-image-shade);}&:focus-visible::-moz-range-thumb{outline:2pxsolidvar(--color-on-image);outline-offset:2px;box-shadow:0002pxvar(--color-focus),000.5pxvar(--color-on-image-shade),03px6px-2pxvar(--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%;}}