網站導覽

v2.1.0
媒體

圖片裁切

在圖片上方疊一個框,標出要保留的部分。

本頁內容

圖片裁切是在圖片上方疊一個框,標出要保留的部分:例如發布前裁切照片、將封面修成橫幅的比例,或在圓形中框出頭像。圖片放在凹槽中。框外的部分會變暗,框的邊緣是疊在圖片上的白線,把手則是四個角落的珍珠圓點和四條邊上的膠囊形。按住或以按鍵操作框時,框內會顯示三分法格線。

圖片裁切

<div class="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66">  <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">  <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">    <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-top"></span>    <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-left"></span>  </div>  <p class="cropper-status" role="status"></p></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="cropper max-w(480) mx-auto" style={{ '--cropper-x': '.16', '--cropper-y': '.14', '--cropper-width': '.62', '--cropper-height': '.66' } as React.CSSProperties}>      <img className="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480" />      <div className="cropper-box" role="application" aria-roledescription="crop box" tabIndex={0} aria-label="Crop the photo">        <span className="cropper-handle cropper-handle-top cropper-handle-left"></span>        <span className="cropper-handle cropper-handle-top"></span>        <span className="cropper-handle cropper-handle-top cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-bottom cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-bottom"></span>        <span className="cropper-handle cropper-handle-bottom cropper-handle-left"></span>        <span className="cropper-handle cropper-handle-left"></span>      </div>      <p className="cropper-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66" {@attach attach}>  <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">  <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">    <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-top"></span>    <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-left"></span>  </div>  <p class="cropper-status" role="status"></p></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="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66">    <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    </div>    <p class="cropper-status" role="status"></p>  </div></template>
拖曳框或把手,或在圖片上拖出新的框。讓框取得焦點後使用方向鍵;按住 Alt 再按方向鍵可調整大小。

幾何資訊是根元素上的四個自訂屬性,每個都是占圖片比例的 0 到 1 之間的值:--cropper-x 和 --cropper-y 從圖片左上角起算,另外還有 --cropper-width 和 --cropper-height。樣式表依據這些值放置框,變暗的範圍也會跟著框走。沒有腳本時,框會停在這些值指定的位置;省略這些值時,框就是整張圖片。

應用程式讀取的值是以圖片本身像素表示的同一個矩形,即 { x, y, width, height }。實際裁切圖片由應用程式負責,請參閱裁切圖片。

#行為

cropper 接收根元素(帶有 cropper 類別的元素)和選項物件,並傳回用來解除行為的函式。它的 value 就是裁切範圍;從外部設定這個值即可移動裁切範圍,這樣做不會觸發任何事件。

app.js
import { cropper } from '@master/ui/behaviors/cropper.js'const root = document.querySelector('.cropper')const crop = cropper(root, { ratio: 16 / 9 })root.addEventListener('change', () => {  const { x, y, width, height } = crop.value  form.elements.crop.value = [x, y, width, height].join(' ')})
  • 框。 拖曳框會移動它,拖曳把手會移動該把手所代表的邊,在框外的圖片上拖曳則會畫出新的框。在框外按下但不拖曳時,框會移到該處,因此不必拖曳也能移動框。框會保持在圖片範圍內,並維持最小尺寸。
  • 圖片的像素。 裁切範圍是以 cropper-image 的 width 和 height 計算。請在這兩個屬性寫入檔案本身的尺寸:這也能避免圖片載入時畫框跳動。
  • 按鍵。 方向鍵每次將裁切範圍移動一個步距,按住 Shift 時移動十個步距。按住 Alt(Mac 上為 Option)時,方向鍵會移動右邊或下邊來調整大小。按右或下會放大,按左或上會縮小。
  • 事件。 裁切範圍每次變動時,框都會觸發 input;拖曳或按鍵操作結束時,觸發一次 change。兩者都會冒泡。
  • 朗讀內容。 每次 change 之後,行為會將裁切尺寸寫入 cropper-status,這是禮貌模式的即時區域,朗讀內容例如「寬 480 像素、高 270 像素,距左側 64 像素、距頂端 96 像素」。傳入 describe 即可改用頁面的語言。

圖片沒有方向之分,因此無論書寫方向為何,框都從左邊和上方定位,方向鍵也都表示左與右。

選項設定內容
ratio框要維持的寬高比,例如 16 / 9。省略時為自由比例,除非根元素的樣式寫了 --cropper-ratio;設為 0 即為自由比例
step方向鍵每次移動裁切範圍的距離,以圖片像素計。預設為圖片長邊的百分之一
min最小的寬度與高度,以圖片像素計。預設為圖片短邊的十分之一
maxZoom沒有範圍輸入元件指定時,平移式裁切的最大縮放倍率。預設為 4
describe將裁切範圍轉為狀態朗讀文字的函式

同一模組中的 cropperFit(picture, crop, options) 會依照行為保存裁切範圍的方式,讓裁切範圍符合圖片。算繪程式可以用它在伺服器上繪製初始的裁切範圍。

#比例

設定比例時,拖曳角落的把手會固定對角的角落,框也會維持比例;拖曳邊上的把手則會以框的中心為基準調整大小。若掛上行為時指定的比例與框目前的比例不同,行為會以框的中心為基準、在面積不變的情況下套用該比例,並觸發 input 和 change:選擇比例就是這樣生效的。

比例

<div class="grid gap-md max-w(480) mx-auto">  <div class="segmented segmented-sm mx-auto" role="radiogroup" aria-label="Proportions">    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="0" checked>Free    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="1/1">1:1    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="4/3">4:3    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="16/9">16:9    </label>  </div>  <div class="cropper" id="banner-crop" style="--cropper-x: .1; --cropper-y: .2; --cropper-width: .8; --cropper-height: .6">    <img class="cropper-image" src="/demo/tide.svg" alt="The tide coming in over flat sand" width="640" height="400">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the banner">      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    </div>    <p class="cropper-status" role="status"></p>  </div>  <p class="m(0) text-sm fg-text-muted text-center" id="banner-crop-value" aria-hidden="true"></p></div><script>addEventListener('DOMContentLoaded', function () {var root = document.getElementById('banner-crop')var readout = document.getElementById('banner-crop-value')var crop = MasterUI.cropper(root)function show() {  var value = crop.value  readout.textContent = value.width + ' × ' + value.height + ' pixels at ' + value.x + ', ' + value.y}root.addEventListener('input', show)document.querySelectorAll('input[name="banner-ratio"]').forEach(function (input) {  input.addEventListener('change', function () {    var parts = input.value.split('/')    crop = MasterUI.cropper(root, { ratio: parts.length > 1 ? parts[0] / parts[1] : 0 })  })})show()})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
選擇比例,再拖曳角落或邊。圖片下方那一行就是目前的值。

在同一個根元素上再次呼叫 cropper 會取代前一次的行為,因此預覽會以新的比例重新掛上行為。MasterUI 是預覽載入的套件包;在專案中,請依照行為一節所示匯入 cropper。框架元件在 ratio 改變時也會這樣做。

#頭像

cropper-pan 會讓框固定在畫框中央,維持 --cropper-ratio 的比例,改為移動框下方的圖片:拖曳可平移,雙指可捏合縮放,按住 Control 或 Command 時滾輪可縮放,觸控板的捏合手勢送出的也正是這種事件。cropper-round 會將框繪製成圓形。裁切範圍的值會多出 zoom:裁切範圍達到圖片允許的最大尺寸時為 1。

aria-controls 指向根元素 id 的範圍輸入元件也能縮放,範圍從它的 min 到 max,並會跟著其他方式造成的縮放更新。它是頁面自己的滑桿,因此可以放在畫框下方、旁邊或工具列中。

頭像

<div class="grid gap-md w(280) mx-auto">  <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">    <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>    <p class="cropper-status" role="status"></p>  </div>  <div class="flex items-center gap-sm fg-text-muted">    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="7" cy="7" r="4.5" /><path d="M10.182 10.182L14 14" /><path d="M5 7L9 7" />    </svg>    <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="7" cy="7" r="4.5" /><path d="M10.182 10.182L14 14" /><path d="M5 7L9 7" /><path d="M7 5L7 9" />    </svg>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import ZoomOutIcon from '@master/icons-react/native/16/soft/zoom-out'import ZoomInIcon from '@master/icons-react/native/16/soft/zoom-in'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="grid gap-md w(280) mx-auto">      <div className="cropper cropper-pan cropper-round" id="avatar-crop" style={{ '--cropper-x': '.1', '--cropper-y': '.18', '--cropper-width': '.8', '--cropper-height': '.64' } as React.CSSProperties}>        <img className="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600" />        <div className="cropper-box" role="application" aria-roledescription="crop box" tabIndex={0} aria-label="Frame your picture"></div>        <p className="cropper-status" role="status"></p>      </div>      <div className="flex items-center gap-sm fg-text-muted">        <ZoomOutIcon className="icon" />        <input type="range" className="slider grow(1)" min="1" max="4" step="any" defaultValue="1.25" aria-controls="avatar-crop" aria-label="Zoom" />        <ZoomInIcon className="icon" />      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import ZoomOutIcon from '@master/icons-svelte/native/16/soft/zoom-out'  import ZoomInIcon from '@master/icons-svelte/native/16/soft/zoom-in'</script><div class="grid gap-md w(280) mx-auto" {@attach attach}>  <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">    <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>    <p class="cropper-status" role="status"></p>  </div>  <div class="flex items-center gap-sm fg-text-muted">    <ZoomOutIcon class="icon" />    <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">    <ZoomInIcon class="icon" />  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import ZoomOutIcon from '@master/icons-vue/native/16/soft/zoom-out'import ZoomInIcon from '@master/icons-vue/native/16/soft/zoom-in'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="grid gap-md w(280) mx-auto">    <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">      <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">      <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>      <p class="cropper-status" role="status"></p>    </div>    <div class="flex items-center gap-sm fg-text-muted">      <ZoomOutIcon class="icon" />      <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">      <ZoomInIcon class="icon" />    </div>  </div></template>
拖曳或捏合圖片,或移動滑桿。讓圓形取得焦點:方向鍵可平移,+ 和 - 可縮放。

無論縮放倍率為何,圖片都會填滿框,因此平移式的裁切範圍一定在圖片內。在按鍵操作上,方向鍵和其他情況一樣移動裁切範圍,按住 Alt 再按方向鍵,或按 + 和 -,會以框的中心為基準縮放。框沒有把手,而框周圍的空間 --cropper-inset 會顯示一圈變暗的圖片,讓讀者看到哪些部分會被捨去。

#裁切圖片

圖片裁切只標出要保留的部分,從不修改檔案本身。可以將這四個數值隨上傳一併送出,在伺服器上裁切;也可以在頁面中用 canvas 裁切:drawImage 會以圖片本身的像素擷取圖片的一部分,而這正是值所使用的單位。

crop.js
/** The part of a loaded picture a crop keeps, as a file. */function cut(image, { x, y, width, height }, type = 'image/webp') {  const canvas = document.createElement('canvas')  canvas.width = width  canvas.height = height  canvas.getContext('2d').drawImage(image, x, y, width, height, 0, 0, width, height)  return new Promise((resolve) => canvas.toBlob(resolve, type))}const file = await cut(document.querySelector('.cropper-image'), crop.value)
  • 圖片必須來自頁面本身的來源,或帶有 crossorigin 並透過 CORS 提供:繪製過其他來源圖片的 canvas 會拒絕匯出內容。
  • 若圖片的 width 和 height 不是檔案本身的尺寸,請先將裁切範圍乘上 image.naturalWidth / width。
  • 圓形裁切仍保存為正方形:頭像會自行繪製成圓形。只有當檔案本身必須是圓形時,才用 arc() 裁剪 canvas。

#鍵盤操作

按鍵動作
ArrowLeft, ArrowRight, ArrowUp, ArrowDown以圖片像素為單位移動裁切框一步,預設為長邊的百分之一;按住 Shift 時移動十步
Alt + ArrowRight, Alt + ArrowDown從遠端邊緣加寬或加高裁切框,固定比例時兩者同時調整;在平移式裁切器上則為縮小
Alt + ArrowLeft, Alt + ArrowUp從遠端邊緣縮窄或縮短裁切框,固定比例時兩者同時調整;在平移式裁切器上則為放大
+, -在平移式裁切器上,以裁切框中心為準放大或縮小

#無障礙

  • 框是唯一的 Tab 停駐點。它設有 role="application":它是單一控制項,擁有其他角色都無法描述的專屬按鍵,這個角色會告訴螢幕閱讀器將方向鍵交給它處理。請依裁切的內容為它命名,並以頁面的語言提供 aria-roledescription,讓它被讀作裁切框,而不是應用程式。
  • 把手不會取得焦點。多出八個 Tab 停駐點,對鍵盤使用者而言並不會比框本身多提供什麼:方向鍵可移動裁切範圍,按住 Alt 再按方向鍵可調整大小,能達到把手所能達到的每一種裁切範圍。移動起始側的邊,等於先移動再調整大小。
  • 每次 change 事件後,cropper-status 會以禮貌模式朗讀裁切範圍的像素尺寸。請從一開始就將它放在標記中,讓螢幕閱讀器在首次朗讀前就能辨識這個區域。
  • 每種拖曳都有替代方式:按鍵、在圖片上按一下將框移到該處,以及縮放滑桿。
  • 請為圖片提供說明內容的 alt:讀者正在決定要保留圖片的哪個部分。
  • 把手的點擊目標為 24px,在觸控螢幕上為 44px,其中繪製的圓點或膠囊形則維持原本大小;圖片周圍的空間也會跟著變大。整個畫框都會接收指標操作,因此請將圖片裁切放在手指不需要捲動經過它的地方,例如對話框或編輯器中。
  • 啟用減少動態效果時,把手按住時不會放大。強制色彩模式下,框以系統外框線繪製,把手使用按鈕色彩,變暗效果則保留。

#React、Svelte 和 Vue

cropper 元件會算繪圖片、框和把手,掛上行為,並支援傳入及傳出裁切範圍。平移式裁切會將連接畫框所需的屬性交給頁面自己的範圍輸入元件。用 npx master-ui add cropper 將元件複製到專案中。元件的建置與使用方式請參閱 React、Svelte 和 Vue。

ui/cropper.tsx
'use client'import { useId, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react'import { cropper, cropperFit, type Crop } from '@master/ui/behaviors/cropper.js'import { useBehavior } from './use-behavior'export type { Crop }/** What the page's range input takes to zoom a panned cropper: spread it on the input. */export interface CropperZoomAttributes {  type: 'range'  min: number  max: number  step: 'any'  defaultValue: number  disabled?: boolean  'aria-controls': string}export interface CropperProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  /** The picture. */  src: string  alt: string  /** The picture's own size, in pixels: the crop is counted in them. */  width: number  height: number  /** The crop, in the picture's pixels, with `zoom` on a panned cropper. */  value?: Crop  defaultValue?: Crop  /** Called as the crop moves. */  onValueChange?: (crop: Crop) => void  /** Called once a drag, a key, a pinch or a turn of the wheel has ended. */  onValueCommit?: (crop: Crop) => void  /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */  ratio?: number  /** The box stays and the picture pans and zooms under it. */  pan?: boolean  /** A round box, for an avatar. */  round?: boolean  /** The least width and height, in the picture's pixels. */  min?: number  /** How far an arrow key moves the crop, in the picture's pixels. */  step?: number  /** The greatest zoom of a panned cropper. */  maxZoom?: number  /** The name of the box: what is cropped. */  label: string  /** What the box is called in place of "application", such as "crop box". */  roleDescription?: string  /** What the status says of a crop after each change, in the page's language. */  describe?: (crop: Crop) => string  /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */  zoom?: (attributes: CropperZoomAttributes) => ReactNode  disabled?: boolean}/** A share of the picture as the behavior writes it. */const share = (part: number) => String(Math.round(part * 1e5) / 1e5)/** A picture with a box over it that says what to keep. */export function Cropper({ src, alt, width, height, value, defaultValue, onValueChange, onValueCommit, ratio, pan, round, min, step, maxZoom = 4, label, roleDescription, describe, zoom, disabled, id, className, style, ...root }: CropperProps) {  const generated = useId()  const name = id ?? generated  const [first] = useState(() => cropperFit({ width, height }, value ?? defaultValue, { ratio, pan, min, zoom: [1, maxZoom] }))  const held = useRef(first)  const ref = useBehavior(cropper, { ratio: ratio ?? 0, step, min, maxZoom, describe }, {    value,    defaultValue,    onValueChange: (next: Crop | null) => { if (!next) return; held.current = next; onValueChange?.(next) },    // The box says change once a gesture or a key has ended.    on: { change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) onValueCommit?.(held.current) } },  })  // The first crop is drawn on the server; after that the behavior writes these properties.  const shares = { '--cropper-x': share(first.x / width), '--cropper-y': share(first.y / height), '--cropper-width': share(first.width / width), '--cropper-height': share(first.height / height), '--cropper-ratio': ratio || undefined }  return (    <>      <div id={name} className={['cropper', pan && 'cropper-pan', round && 'cropper-round', className].filter(Boolean).join(' ')} style={{ ...shares, ...style } as CSSProperties} ref={ref} {...root}>        <img className="cropper-image" src={src} alt={alt} width={width} height={height} />        <div className="cropper-box" role="application" tabIndex={disabled ? -1 : 0} aria-label={label} aria-roledescription={roleDescription} aria-disabled={disabled || undefined}>          {pan ? null : (            <>              <span className="cropper-handle cropper-handle-top cropper-handle-left" />              <span className="cropper-handle cropper-handle-top" />              <span className="cropper-handle cropper-handle-top cropper-handle-right" />              <span className="cropper-handle cropper-handle-right" />              <span className="cropper-handle cropper-handle-bottom cropper-handle-right" />              <span className="cropper-handle cropper-handle-bottom" />              <span className="cropper-handle cropper-handle-bottom cropper-handle-left" />              <span className="cropper-handle cropper-handle-left" />            </>          )}        </div>        <p className="cropper-status" role="status" />      </div>      {pan && zoom?.({ type: 'range', min: 1, max: maxZoom, step: 'any', defaultValue: first.zoom ?? 1, disabled, 'aria-controls': name })}    </>  )}
ui/Cropper.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  import type { Crop } from '@master/ui/behaviors/cropper.js'  export type { Crop }  /** What the page's range input takes to zoom a panned cropper: spread it on the input. */  export interface CropperZoomAttributes {    type: 'range'    min: number    max: number    step: 'any'    value: number    disabled?: boolean    'aria-controls': string  }  export interface CropperProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The picture. */    src: string    alt: string    /** The picture's own size, in pixels: the crop is counted in them. */    width: number    height: number    /** The crop, in the picture's pixels, with `zoom` on a panned cropper. Bind it, or leave it out. */    value?: Crop    /** Called as the crop moves. */    onValueChange?: (crop: Crop) => void    /** Called once a drag, a key, a pinch or a turn of the wheel has ended. */    onValueCommit?: (crop: Crop) => void    /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */    ratio?: number    /** The box stays and the picture pans and zooms under it. */    pan?: boolean    /** A round box, for an avatar. */    round?: boolean    /** The least width and height, in the picture's pixels. */    min?: number    /** How far an arrow key moves the crop, in the picture's pixels. */    step?: number    /** The greatest zoom of a panned cropper. */    maxZoom?: number    /** The name of the box: what is cropped. */    label: string    /** What the box is called in place of "application", such as "crop box". */    roleDescription?: string    /** What the status says of a crop after each change, in the page's language. */    describe?: (crop: Crop) => string    /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */    zoom?: Snippet<[CropperZoomAttributes]>    disabled?: boolean  }</script><script lang="ts">  import { untrack } from 'svelte'  import { cropper, cropperFit } from '@master/ui/behaviors/cropper.js'  import { behavior } from './behavior.svelte.js'  let { src, alt, width, height, value = $bindable(), onValueChange, onValueCommit, ratio, pan, round, min, step, maxZoom = 4, label, roleDescription, describe, zoom, disabled, id, class: className, ...root }: CropperProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  const first = untrack(() => cropperFit({ width, height }, value, { ratio, pan, min, zoom: [1, maxZoom] }))  // Svelte writes a style again whenever its owner changes it, so it writes the crop the behavior holds.  let crop = $state(first)  const attach = behavior(cropper, () => ({ ratio: ratio ?? 0, step, min, maxZoom, describe }), {    value: () => value,    change: (next) => { if (!next) return; value = crop = next; onValueChange?.(next) },    settled: (held) => { if (held) crop = held },    // The box says change once a gesture or a key has ended.    on: { change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) onValueCommit?.(crop) } },  })  /** A share of the picture as the behavior writes it. */  const share = (part: number) => String(Math.round(part * 1e5) / 1e5)</script><!--  @component  A picture with a box over it that says what to keep.--><div id={name} class={['cropper', pan && 'cropper-pan', round && 'cropper-round', className]} style:--cropper-x={share(crop.x / width)} style:--cropper-y={share(crop.y / height)} style:--cropper-width={share(crop.width / width)} style:--cropper-height={share(crop.height / height)} style:--cropper-ratio={ratio || undefined} {@attach attach} {...root}>  <img class="cropper-image" {src} {alt} {width} {height} />  <!-- The box is one control that the keys move and size: an application of its own. -->  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->  <div class="cropper-box" role="application" tabindex={disabled ? -1 : 0} aria-label={label} aria-roledescription={roleDescription} aria-disabled={disabled || undefined}>    {#if !pan}      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    {/if}  </div>  <p class="cropper-status" role="status"></p></div>{#if pan}  {@render zoom?.({ type: 'range', min: 1, max: maxZoom, step: 'any', value: first.zoom ?? 1, disabled, 'aria-controls': name })}{/if}
ui/Cropper.vue
<script lang="ts">import type { Crop } from '@master/ui/behaviors/cropper.js'export type { Crop }/** What the page's range input takes to zoom a panned cropper: bind it on the input. */export interface CropperZoomAttributes {  type: 'range'  min: number  max: number  step: 'any'  value: number  disabled?: boolean  'aria-controls': string}</script><script setup lang="ts">import { useAttrs, useId, useTemplateRef, type Ref } from 'vue'import { cropper, cropperFit } from '@master/ui/behaviors/cropper.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { width, height, ratio, pan, min, step, maxZoom = 4, describe } = defineProps<{  /** The picture. */  src: string  alt: string  /** The picture's own size, in pixels: the crop is counted in them. */  width: number  height: number  /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */  ratio?: number  /** The box stays and the picture pans and zooms under it. */  pan?: boolean  /** A round box, for an avatar. */  round?: boolean  /** The least width and height, in the picture's pixels. */  min?: number  /** How far an arrow key moves the crop, in the picture's pixels. */  step?: number  /** The greatest zoom of a panned cropper. */  maxZoom?: number  /** The name of the box: what is cropped. */  label: string  /** What the box is called in place of "application", such as "crop box". */  roleDescription?: string  /** What the status says of a crop after each change, in the page's language. */  describe?: (crop: Crop) => string  disabled?: boolean}>()/** The crop, in the picture's pixels, with `zoom` on a panned cropper: `v-model`. It changes as the crop moves. */const model = defineModel<Crop>()const emit = defineEmits<{  /** The crop, once a drag, a key, a pinch or a turn of the wheel has ended. */  valueCommit: [value: Crop]}>()defineSlots<{  /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */  zoom?: (attributes: CropperZoomAttributes) => unknown}>()/* A picture with a box over it that says what to keep. */const generated = useId()const attrs = useAttrs()const name = () => (attrs.id as string | undefined) ?? generatedconst first = cropperFit({ width, height }, model.value, { ratio, pan, min, zoom: [1, maxZoom] })const root = useTemplateRef<HTMLDivElement>('root')const current = useBehavior(root, cropper, () => ({ ratio: ratio ?? 0, step, min, maxZoom, describe }), model as Ref<Crop | null | undefined>, {  // The box says change once a gesture or a key has ended.  change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) emit('valueCommit', crop()) },})// Vue writes a style again each time it renders, so it writes the crop the behavior holds, not the first one.const crop = () => current() ?? first/** A share of the picture as the behavior writes it. */const share = (part: number) => String(Math.round(part * 1e5) / 1e5)const shares = () => {  const { x, y, width: across, height: down } = crop()  return { '--cropper-x': share(x / width), '--cropper-y': share(y / height), '--cropper-width': share(across / width), '--cropper-height': share(down / height), '--cropper-ratio': ratio || undefined }}</script><template>  <div class="cropper" :class="{ 'cropper-pan': pan, 'cropper-round': round }" :style="shares()" ref="root" v-bind="$attrs" :id="name()">    <img class="cropper-image" :src="src" :alt="alt" :width="width" :height="height">    <div class="cropper-box" role="application" :tabindex="disabled ? -1 : 0" :aria-label="label" :aria-roledescription="roleDescription" :aria-disabled="disabled || undefined">      <template v-if="!pan">        <span class="cropper-handle cropper-handle-top cropper-handle-left" />        <span class="cropper-handle cropper-handle-top" />        <span class="cropper-handle cropper-handle-top cropper-handle-right" />        <span class="cropper-handle cropper-handle-right" />        <span class="cropper-handle cropper-handle-bottom cropper-handle-right" />        <span class="cropper-handle cropper-handle-bottom" />        <span class="cropper-handle cropper-handle-bottom cropper-handle-left" />        <span class="cropper-handle cropper-handle-left" />      </template>    </div>    <p class="cropper-status" role="status" />  </div>  <!-- Vue writes a field's value with every render, so the zoom it is given is the one the behavior holds. -->  <slot v-if="pan" name="zoom" v-bind="{ type: 'range', min: 1, max: maxZoom, step: 'any', value: crop().zoom ?? 1, disabled, 'aria-controls': name() } as CropperZoomAttributes" /></template>

#類別

類別說明
cropper外框:一個凹槽,圖片與其邊緣相距 --cropper-inset,上方疊著裁切框。整個外框都接收指標操作
cropper-pan裁切框固定在外框中央,比例為 --cropper-ratio,圖片在框下方平移與縮放搭配 cropper 使用
cropper-round裁切框為圓形;框不是正方形時則為框內的橢圓。適用於頭像搭配 cropper 使用
cropper-image圖片。寬度與高度設為檔案本身的像素尺寸,裁切範圍以此計算
cropper-box裁切框:只占一個 Tab 停駐點,可用方向鍵移動與調整大小,位置由四個屬性決定。框外的圖片會調暗;按住或以鍵盤操作時會顯示三分線
cropper-handle供指標拖曳的把手:操作範圍 24px,低精確度指標為 44px。位於邊緣時顯示珠光膠囊,位於角落時顯示珠光圓點。修飾類別指定它移動的邊緣
cropper-handle-top把手移動上緣搭配 cropper-handle 使用
cropper-handle-bottom把手移動下緣搭配 cropper-handle 使用
cropper-handle-left把手移動左緣搭配 cropper-handle 使用
cropper-handle-right把手移動右緣搭配 cropper-handle 使用
cropper-status禮貌型(polite)即時區域,畫面上隱藏但會被朗讀。每次變更後,腳本會將裁切尺寸寫入其中

#自訂屬性

屬性預設值說明
--cropper-x0裁切範圍的左緣,以占圖片寬度的比例表示,範圍 0 到 1;由腳本寫入
--cropper-y0裁切範圍的上緣,以占圖片高度的比例表示
--cropper-width1裁切範圍的寬度,以占圖片寬度的比例表示
--cropper-height1裁切範圍的高度,以占圖片高度的比例表示
--cropper-ratio1平移式裁切框的寬高比。腳本會將維持的比例寫在這裡,也會讀取標記中寫入的值
--cropper-inset1rem圖片與外框之間的空間:低精確度指標為 1.375rem,讓位於圖片邊緣的把手能完整顯示;平移式裁切框周圍為 1.5rem
--cropper-radiusvar(--radius-surface)外框圓角
--cropper-target1.5rem把手操作範圍的大小;低精確度指標為 2.75rem。其中繪製的標記大小不變

#原始碼

@master/ui/components/cropper.css
/* * Cropper: a picture with a box over it that says what to keep. * The picture rests in a well, --cropper-inset in from its edge, so the handles of a box that reaches the * picture's edge still have room. What lies outside the box is dimmed: the box casts a wide shadow of * --color-image-dim, clipped to the picture, so the dim follows the box's corner, round included, and never * spills past the picture. The box's own edge is the line drawn over a picture (white with a dark shade, * in both themes, as on a comparison), its handles are pearl discs at the corners and pills on the edges, * and the rule of thirds appears inside it while it is held or focused from the keyboard. * * The geometry is four custom properties, shares of the picture from 0 to 1: --cropper-x and --cropper-y * from its top left corner, --cropper-width and --cropper-height. A script writes them; the stylesheet * places the box from them, and with no script the box stays where they put it, the whole picture by default. * A picture has no direction, so the box is placed from the left and the top in every writing direction. * * Panned (cropper-pan): the box stays in the middle of the frame, at the proportions of --cropper-ratio, and * the picture moves and scales under it from the same four properties. Round (cropper-round) draws the box * as a circle, for an avatar. * * A handle's target is 24px, 44px on a coarse pointer, while the disc or the pill drawn in it keeps its * size; the inset grows with the target. Edge handles step aside when the box is too small to hold them. */@layer components.ui {  .cropper {    --cropper-x: 0;    --cropper-y: 0;    --cropper-width: 1;    --cropper-height: 1;    --cropper-ratio: 1;    --cropper-inset: 1rem;    --cropper-radius: var(--radius-surface);    --cropper-target: 1.5rem;    position: relative;    display: block;    box-sizing: border-box;    min-width: 0;    margin: 0;    padding: var(--cropper-inset);    overflow: clip;    border-radius: calc(var(--cropper-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--color-surface-inset);    box-shadow: var(--shadow-pressed);    cursor: crosshair;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-touch-callout: none;    -webkit-tap-highlight-color: transparent;    isolation: isolate;    @media (pointer: coarse) {      --cropper-target: 2.75rem;      --cropper-inset: 1.375rem;    }    /*     * Panned: the frame holds the box, --cropper-inset in from every edge, and the picture is placed under it     * so that the part the four properties name fills the box exactly.     */    &.cropper-pan {      --cropper-inset: 1.5rem;      display: grid;      cursor: grab;      &:active {        cursor: grabbing;      }      /* The inward line every picture gets, over the picture that now runs to the frame's edge. */      &::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;      }      .cropper-image {        position: absolute;        top: var(--cropper-inset);        left: var(--cropper-inset);        width: calc((100% - var(--cropper-inset) * 2) / var(--cropper-width));        max-width: none;        translate: calc(var(--cropper-x) * -100%) calc(var(--cropper-y) * -100%);        outline: 0;      }      .cropper-box {        position: relative;        inset: auto;        width: 100%;        height: auto;        aspect-ratio: var(--cropper-ratio);        cursor: inherit;      }    }    &.cropper-round .cropper-box {      border-radius: 50%;      corner-shape: round;    }    &:has(.cropper-box[aria-disabled="true"]) {      cursor: default;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /* The picture: as wide as the well, at its own proportions, from the width and height it is given. */  .cropper-image {    display: block;    width: 100%;    max-width: 100%;    height: auto;    margin: 0;    border: 0;    outline: .5px solid var(--color-line-image-strong);    outline-offset: -.5px;    pointer-events: none;    -webkit-user-drag: none;  }  /*   * The box: placed from the four properties, inside the well's inset. Its edge is a white line with a   * dark shade; ::before casts the dim over the rest of the picture and ::after holds the thirds.   */  .cropper-box {    position: absolute;    top: calc(var(--cropper-inset) + var(--cropper-y) * (100% - var(--cropper-inset) * 2));    left: calc(var(--cropper-inset) + var(--cropper-x) * (100% - var(--cropper-inset) * 2));    width: calc(var(--cropper-width) * (100% - var(--cropper-inset) * 2));    height: calc(var(--cropper-height) * (100% - var(--cropper-inset) * 2));    box-sizing: border-box;    container: cropper-box / size;    margin: 0;    padding: 0;    border: 0;    outline: none;    box-shadow: inset 0 0 0 1px var(--color-on-image), 0 0 0 .5px var(--color-on-image-shade), 0 0 6px var(--color-on-image-shade);    cursor: move;    touch-action: none;    /* Its own layer: the dim it casts lies under its focus ring, and over the picture. */    isolation: isolate;    /*     * The dim: a shadow wide enough for any picture, clipped to the picture. The clip is the picture's own     * edge, measured from the box: it starts x / width box-widths to the left, and so on for each side.     */    &::before {      content: '';      position: absolute;      inset: 0;      z-index: -1;      border-radius: inherit;      corner-shape: inherit;      box-shadow: 0 0 0 9999px var(--color-image-dim);      clip-path: polygon(        calc(var(--cropper-x) / var(--cropper-width) * -100%) calc(var(--cropper-y) / var(--cropper-height) * -100%),        calc((1 - var(--cropper-x)) / var(--cropper-width) * 100%) calc(var(--cropper-y) / var(--cropper-height) * -100%),        calc((1 - var(--cropper-x)) / var(--cropper-width) * 100%) calc((1 - var(--cropper-y)) / var(--cropper-height) * 100%),        calc(var(--cropper-x) / var(--cropper-width) * -100%) calc((1 - var(--cropper-y)) / var(--cropper-height) * 100%)      );      pointer-events: none;    }    /* The rule of thirds: two fine lines each way, shown while the box is held or keyed. */    &::after {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      background:        linear-gradient(to right, transparent calc(100% / 3 - .5px), var(--color-on-image) 0 calc(100% / 3 + .5px), transparent 0 calc(200% / 3 - .5px), var(--color-on-image) 0 calc(200% / 3 + .5px), transparent 0),        linear-gradient(to bottom, transparent calc(100% / 3 - .5px), var(--color-on-image) 0 calc(100% / 3 + .5px), transparent 0 calc(200% / 3 - .5px), var(--color-on-image) 0 calc(200% / 3 + .5px), transparent 0);      opacity: 0;      pointer-events: none;      transition: opacity var(--duration-quick) var(--easing-glide);    }    /* As on a comparison's grip: an ink ring at the edge and a white one outside it, so one reads on any picture or well. */    &:focus-visible {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: inset 0 0 0 1px var(--color-on-image), 0 0 0 2px var(--color-focus), 0 0 6px var(--color-on-image-shade);    }    &:focus-visible::after {      opacity: .6;    }    &[aria-disabled="true"] {      cursor: default;      .cropper-handle {        display: none;      }    }    @media (forced-colors: active) {      outline: 2px solid CanvasText;      outline-offset: -1px;      &::before {        forced-color-adjust: none;      }      &:focus-visible {        outline-color: Highlight;      }    }  }  /* While the box, a handle or the picture under a panned box is held, the thirds show; not on a disabled box. */  .cropper:active .cropper-box:not([aria-disabled="true"])::after {    opacity: .6;  }  /*   * A handle: a target as large as --cropper-target, centered on a corner or on the middle of an edge, and   * a mark drawn in it that keeps its size. Its modifiers name the edges it moves: one for an edge, two for   * a corner.   */  .cropper-handle {    position: absolute;    top: 50%;    left: 50%;    width: var(--cropper-target);    height: var(--cropper-target);    translate: -50% -50%;    touch-action: none;    /* The mark: a pill on an edge, turned with the edge. */    &::after {      content: '';      position: absolute;      inset: 0;      width: 1.25rem;      height: .375rem;      margin: auto;      border-radius: 999px;      corner-shape: round;      @apply --surface-thumb;      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 2px 6px -1px var(--color-on-image-shade);      transition: scale var(--duration-quick) var(--easing-glide);    }    &.cropper-handle-top {      top: 0;      cursor: ns-resize;    }    &.cropper-handle-bottom {      top: 100%;      cursor: ns-resize;    }    &.cropper-handle-left {      left: 0;      cursor: ew-resize;    }    &.cropper-handle-right {      left: 100%;      cursor: ew-resize;    }    &.cropper-handle-left::after, &.cropper-handle-right::after {      width: .375rem;      height: 1.25rem;    }    /* A corner: a disc, over the edges it meets. */    &:is(.cropper-handle-top, .cropper-handle-bottom):is(.cropper-handle-left, .cropper-handle-right) {      z-index: 1;      &::after {        width: .75rem;        height: .75rem;      }    }    &.cropper-handle-top.cropper-handle-left, &.cropper-handle-bottom.cropper-handle-right {      cursor: nwse-resize;    }    &.cropper-handle-top.cropper-handle-right, &.cropper-handle-bottom.cropper-handle-left {      cursor: nesw-resize;    }    @media (hover: hover) {      &:hover::after {        scale: 1.2;      }    }    &:active::after {      scale: 1.2;    }    @media (prefers-reduced-motion: reduce) {      &::after {        transition: none;      }      &:hover::after, &:active::after {        scale: none;      }    }    @media (forced-colors: active) {      &::after {        forced-color-adjust: none;        background: ButtonText;        box-shadow: 0 0 0 1px ButtonFace;      }    }  }  /*   * An edge's handle steps aside when the box is too small to hold it apart from the corners. On a coarse   * pointer the targets are 44px, and an edge's would reach into a corner's until the box is twice that.   */  @container cropper-box (width < 4.5rem) {    .cropper-handle.cropper-handle-top:not(.cropper-handle-left, .cropper-handle-right),    .cropper-handle.cropper-handle-bottom:not(.cropper-handle-left, .cropper-handle-right) {      display: none;    }  }  @container cropper-box (height < 4.5rem) {    .cropper-handle.cropper-handle-left:not(.cropper-handle-top, .cropper-handle-bottom),    .cropper-handle.cropper-handle-right:not(.cropper-handle-top, .cropper-handle-bottom) {      display: none;    }  }  @media (pointer: coarse) {    @container cropper-box (width < 5.5rem) {      .cropper-handle.cropper-handle-top:not(.cropper-handle-left, .cropper-handle-right),      .cropper-handle.cropper-handle-bottom:not(.cropper-handle-left, .cropper-handle-right) {        display: none;      }    }    @container cropper-box (height < 5.5rem) {      .cropper-handle.cropper-handle-left:not(.cropper-handle-top, .cropper-handle-bottom),      .cropper-handle.cropper-handle-right:not(.cropper-handle-top, .cropper-handle-bottom) {        display: none;      }    }  }  /* What the script says after a change, for assistive technology only. */  .cropper-status {    position: absolute;    width: 1px;    height: 1px;    margin: -1px;    padding: 0;    overflow: hidden;    clip-path: inset(50%);    white-space: nowrap;  }}