导航

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 input 一致
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手柄使用横跨框架的 range input,隐藏轨道,并提供可用拇指拖动的握柄。根据移动手柄所产生的效果为控件命名。

#自定义属性

属性默认值说明
--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%;  }}