이미지 자르기 컴포넌트는 이미지에서 남길 부분을 상자로 표시합니다. 게시하기 전에 사진을 자르거나, 커버 이미지를 배너 비율에 맞춰 다듬거나, 아바타를 원 안에 맞출 때 사용합니다. 이미지는 오목한 영역에 놓입니다. 상자 바깥 부분은 어둡게 처리되고, 상자의 테두리는 이미지 위에 그리는 흰 선이며, 핸들은 모서리의 진주빛 원반과 변의 알약 모양입니다. 상자를 잡고 있거나 키로 조작하는 동안에는 상자 안에 3분할 안내선이 나타납니다.
상자나 핸들을 드래그하거나, 이미지 위를 가로질러 새 상자를 그려 보세요. 상자에 포커스를 두고 방향키를 사용하세요. 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가 발생할 때마다 동작은 자르기 영역의 크기와 위치를 polite 라이브 영역인 cropper-status에 기록합니다(예: "480 by 270 pixels, 64 from the left and 96 from the top"). 페이지 언어로 안내하려면 describe를 전달하세요.
이미지에는 방향이 없으므로, 어떤 쓰기 방향에서든 상자는 왼쪽과 위쪽을 기준으로 배치되며 방향키도 왼쪽과 오른쪽을 그대로 뜻합니다.
옵션
설정하는 내용
ratio
상자가 유지하는 너비 대 높이의 비율입니다(예: 16 / 9). 생략하면 루트의 스타일에 --cropper-ratio가 작성되어 있지 않은 한 자유 비율이며, 0을 지정해도 자유 비율이 됩니다
step
방향키 한 번으로 자르기 영역이 이동하는 거리로, 이미지의 픽셀 단위입니다. 기본값은 이미지의 긴 변의 1/100입니다
min
최소 너비와 높이로, 이미지의 픽셀 단위입니다. 기본값은 이미지의 짧은 변의 1/10입니다
maxZoom
범위 입력 요소가 따로 지정하지 않을 때 이동 모드 이미지 자르기가 확대하는 최대 배율입니다. 기본값은 4입니다
describe
자르기 영역을 받아 상태 영역이 안내할 문구를 반환하는 함수입니다
같은 모듈의 cropperFit(picture, crop, options)는 동작이 처리하는 방식대로 자르기 영역을 이미지에 맞춥니다. 렌더러는 이 함수로 서버에서 첫 자르기 영역을 그립니다.
비율을 지정하면 모서리 핸들은 맞은편 모서리를 고정하고 상자의 비율을 유지하며, 변의 핸들은 상자의 가운데를 기준으로 크기를 바꿉니다. 상자가 갖고 있지 않은 비율로 동작을 연결하면, 동작은 같은 면적을 유지한 채 상자의 가운데를 기준으로 그 비율을 적용하고 input과 change를 발생시킵니다. 비율 선택은 이렇게 적용됩니다.
한 루트에서 cropper를 다시 호출하면 첫 번째 호출을 대체하므로, 이 미리보기는 새 비율로 동작을 다시 연결합니다. MasterUI는 미리보기가 불러오는 번들입니다. 프로젝트에서는 동작 섹션처럼 cropper를 import하세요. 프레임워크 컴포넌트도 ratio가 바뀌면 같은 방식으로 처리합니다.
cropper-pan은 상자를 --cropper-ratio의 비율로 프레임 가운데에 고정하고, 그 대신 아래의 이미지를 움직입니다. 드래그하면 이미지가 이동하고, 두 손가락으로 핀치하면 확대·축소되며, Control 또는 Command 키를 누른 채 휠을 굴리면 확대·축소됩니다. 트랙패드의 핀치도 이 입력을 보냅니다. cropper-round는 상자를 원으로 그립니다. 자르기 영역의 값에는 zoom이 추가되며, 자르기 영역이 이미지가 허용하는 만큼 클 때 1입니다.
aria-controls로 루트의 id를 가리키는 범위 입력 요소도 min부터 max까지 루트를 확대·축소하며, 다른 방법으로 확대·축소해도 그 값을 따라갑니다. 이 입력 요소는 페이지 자체의 슬라이더여서 프레임 아래나 옆, 도구 모음 안 어디에든 둘 수 있습니다.
아바타
<divclass="gridgap-mdw(280)mx-auto"><divclass="cropper cropper-pan cropper-round"id="avatar-crop"style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64"><imgclass="cropper-image"src="/demo/cairn.svg"alt="A cairn of stones on a ridge"width="480"height="600"><divclass="cropper-box"role="application"aria-roledescription="crop box"tabindex="0"aria-label="Frame your picture"></div><pclass="cropper-status"role="status"></p></div><divclass="flexitems-centergap-smfg-text-muted"><svgclass="icon"viewBox="0 0 16 16"fill="none"stroke="currentColor"stroke-width="1"stroke-linecap="round"stroke-linejoin="round"aria-hidden="true"><circlecx="7"cy="7"r="4.5"/><pathd="M10.182 10.182L14 14"/><pathd="M5 7L9 7"/></svg><inputtype="range"class="slider grow(1)"min="1"max="4"step="any"value="1.25"aria-controls="avatar-crop"aria-label="Zoom"><svgclass="icon"viewBox="0 0 16 16"fill="none"stroke="currentColor"stroke-width="1"stroke-linecap="round"stroke-linejoin="round"aria-hidden="true"><circlecx="7"cy="7"r="4.5"/><pathd="M10.182 10.182L14 14"/><pathd="M5 7L9 7"/><pathd="M7 5L7 9"/></svg></div></div><scripttype="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'exportfunctionExample(){const root =useRef<HTMLDivElement>(null)useEffect(()=>attach(root.current!),[])return(<divref={root}className="gridgap-mdw(280)mx-auto"><divclassName="cropper cropper-pan cropper-round"id="avatar-crop"style={{'--cropper-x':'.1','--cropper-y':'.18','--cropper-width':'.8','--cropper-height':'.64'}asReact.CSSProperties}><imgclassName="cropper-image"src="/demo/cairn.svg"alt="A cairn of stones on a ridge"width="480"height="600"/><divclassName="cropper-box"role="application"aria-roledescription="crop box"tabIndex={0}aria-label="Frame your picture"></div><pclassName="cropper-status"role="status"></p></div><divclassName="flexitems-centergap-smfg-text-muted"><ZoomOutIconclassName="icon"/><inputtype="range"className="slider grow(1)"min="1"max="4"step="any"defaultValue="1.25"aria-controls="avatar-crop"aria-label="Zoom"/><ZoomInIconclassName="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><divclass="gridgap-mdw(280)mx-auto"{@attach attach}><divclass="cropper cropper-pan cropper-round"id="avatar-crop"style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64"><imgclass="cropper-image"src="/demo/cairn.svg"alt="A cairn of stones on a ridge"width="480"height="600"><divclass="cropper-box"role="application"aria-roledescription="crop box"tabindex="0"aria-label="Frame your picture"></div><pclass="cropper-status"role="status"></p></div><divclass="flexitems-centergap-smfg-text-muted"><ZoomOutIconclass="icon"/><inputtype="range"class="slider grow(1)"min="1"max="4"step="any"value="1.25"aria-controls="avatar-crop"aria-label="Zoom"><ZoomInIconclass="icon"/></div></div>
<scriptsetup>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><divref="root"class="gridgap-mdw(280)mx-auto"><divclass="cropper cropper-pan cropper-round"id="avatar-crop"style="--cropper-x:.1; --cropper-y:.18; --cropper-width:.8; --cropper-height:.64"><imgclass="cropper-image"src="/demo/cairn.svg"alt="A cairn of stones on a ridge"width="480"height="600"><divclass="cropper-box"role="application"aria-roledescription="crop box"tabindex="0"aria-label="Frame your picture"></div><pclass="cropper-status"role="status"></p></div><divclass="flexitems-centergap-smfg-text-muted"><ZoomOutIconclass="icon"/><inputtype="range"class="slider grow(1)"min="1"max="4"step="any"value="1.25"aria-controls="avatar-crop"aria-label="Zoom"><ZoomInIconclass="icon"/></div></div></template>
이미지를 드래그하거나 핀치하거나 슬라이더를 움직여 보세요. 원에 포커스를 두면 방향키로 이동하고 +와 - 키로 확대·축소합니다.
이미지는 어떤 배율에서든 상자를 가득 채우므로, 이동 모드의 자르기 영역은 항상 이미지 안에 있습니다. 키 조작에서 방향키는 다른 곳과 마찬가지로 자르기 영역을 옮기며, Alt 키와 방향키, 또는 +와 - 키는 상자의 가운데를 기준으로 확대·축소합니다. 상자에는 핸들이 없으며, 상자 주변의 여백인 --cropper-inset에 어둡게 처리한 이미지가 고리 모양으로 보이므로 사용자는 무엇이 잘려 나가는지 알 수 있습니다.
이미지 자르기는 어느 부분을 남길지 알려 줄 뿐, 파일 자체는 건드리지 않습니다. 업로드할 때 네 숫자를 함께 보내 서버에서 자르거나, 페이지에서 캔버스로 자르세요. drawImage는 이미지의 일부를 이미지 자체의 픽셀 단위로 받으며, 값이 바로 그 형식입니다.
crop.js
/** The part of a loaded picture a crop keeps, as a file. */functioncut(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)returnnewPromise((resolve)=> canvas.toBlob(resolve, type))}const file =awaitcut(document.querySelector('.cropper-image'), crop.value)
이미지는 페이지와 같은 출처에서 가져오거나, crossorigin을 지정하고 CORS로 제공해야 합니다. 다른 출처의 이미지를 그린 캔버스는 그 내용을 돌려주지 않습니다.
이미지의 width와 height가 파일 자체의 크기가 아니라면 먼저 자르기 영역에 image.naturalWidth / width를 곱해 크기를 맞추세요.
원형으로 표시해도 자르기 영역은 정사각형으로 유지됩니다. 아바타는 스스로 원형으로 그려지기 때문입니다. 파일 자체가 원형이어야 할 때만 arc()로 캔버스를 잘라 내세요.
탭 순서에서 멈추는 곳은 상자 하나뿐입니다. 상자에는 role="application"이 설정됩니다. 다른 어떤 역할로도 설명할 수 없는 자체 키 조작을 가진 단일 컨트롤이며, 이 역할은 스크린 리더에게 방향키를 상자로 넘기라고 알립니다. 무엇을 자르는지를 이름으로 지정하고, 애플리케이션이 아니라 자르기 상자로 안내되도록 페이지 언어로 된 aria-roledescription을 지정하세요.
핸들은 포커스를 받지 않습니다. 탭 순서에서 멈추는 곳이 여덟 개 더 늘어나도 키보드 사용자에게 상자가 알려 주지 않는 정보는 없습니다. 방향키로 자르기 영역을 옮기고 Alt 키와 방향키로 크기를 바꾸면 핸들로 만들 수 있는 모든 자르기 영역을 만들 수 있습니다. 시작 쪽 변을 옮기는 것은 이동한 뒤 크기를 바꾸는 것과 같습니다.
변경될 때마다 cropper-status가 현재 읽는 내용을 끊지 않고 자르기 영역의 크기를 픽셀 단위로 안내합니다. 스크린 리더가 처음 안내하기 전에 이 영역을 인식할 수 있도록 처음부터 마크업에 두세요.
모든 드래그에는 다른 방법이 있습니다. 키 조작, 이미지를 눌러 상자를 그 위치로 옮기기, 확대·축소 슬라이더입니다.
이미지가 무엇을 보여 주는지 설명하는 alt를 지정하세요. 사용자는 이미지의 어느 부분을 남길지 결정하는 중입니다.
핸들의 조작 영역은 24px이고 터치 화면에서는 44px이며, 그 안에 그린 원반이나 알약 모양은 크기를 유지합니다. 이미지 주변의 여백도 함께 커집니다. 프레임 전체가 포인터 입력을 받으므로, 대화 상자나 편집기처럼 손가락으로 스크롤해 지나칠 필요가 없는 곳에 이미지 자르기를 두세요.
동작 줄이기 설정이 켜져 있으면 핸들을 잡아도 커지지 않습니다. 강제 색상 모드에서는 상자를 시스템 윤곽선으로, 핸들을 버튼 색으로 그리며 어둡게 처리한 부분은 유지합니다.
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'exporttype{ Crop }/** What the page's range input takes to zoom a panned cropper: spread it on the input. */exportinterfaceCropperZoomAttributes{type:'range'min:numbermax:numberstep:'any'defaultValue:numberdisabled?:boolean'aria-controls':string}exportinterfaceCropperPropsextendsOmit<ComponentProps<'div'>,'defaultValue'|'children'|'ref'>{/** The picture. */src:stringalt:string/** The picture's own size, in pixels: the crop is counted in them. */width:numberheight:number/** The crop, in the picture's pixels, with `zoom` on a panned cropper. */value?:CropdefaultValue?: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)=>ReactNodedisabled?:boolean}/** A share of the picture as the behavior writes it. */constshare=(part:number)=>String(Math.round(part *1e5)/1e5)/** A picture with a box over it that says what to keep. */exportfunctionCropper({ 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 ?? generatedconst[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.targetasElement).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(<><divid={name}className={['cropper', pan &&'cropper-pan', round &&'cropper-round', className].filter(Boolean).join(' ')}style={{...shares,...style }asCSSProperties}ref={ref}{...root}><imgclassName="cropper-image"src={src}alt={alt}width={width}height={height}/><divclassName="cropper-box"role="application"tabIndex={disabled ?-1:0}aria-label={label}aria-roledescription={roleDescription}aria-disabled={disabled ||undefined}>{pan ?null:(<><spanclassName="cropper-handle cropper-handle-top cropper-handle-left"/><spanclassName="cropper-handle cropper-handle-top"/><spanclassName="cropper-handle cropper-handle-top cropper-handle-right"/><spanclassName="cropper-handle cropper-handle-right"/><spanclassName="cropper-handle cropper-handle-bottom cropper-handle-right"/><spanclassName="cropper-handle cropper-handle-bottom"/><spanclassName="cropper-handle cropper-handle-bottom cropper-handle-left"/><spanclassName="cropper-handle cropper-handle-left"/></>)}</div><pclassName="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
<scriptlang="ts"module>importtype{ Snippet }from'svelte'importtype{ HTMLAttributes }from'svelte/elements'importtype{ Crop }from'@master/ui/behaviors/cropper.js'exporttype{ Crop }/** What the page's range input takes to zoom a panned cropper: spread it on the input. */exportinterfaceCropperZoomAttributes{type:'range'min:numbermax:numberstep:'any'value:numberdisabled?:boolean'aria-controls':string}exportinterfaceCropperPropsextendsOmit<HTMLAttributes<HTMLDivElement>,'children'>{/** The picture. */src:stringalt:string/** The picture's own size, in pixels: the crop is counted in them. */width:numberheight: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><scriptlang="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.targetasElement).classList.contains('cropper-box'))onValueCommit?.(crop)}},})/** A share of the picture as the behavior writes it. */constshare=(part:number)=>String(Math.round(part *1e5)/1e5)</script><!--@component A picture with a box over it that says what to keep.--><divid={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}><imgclass="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 --><divclass="cropper-box"role="application"tabindex={disabled ?-1:0}aria-label={label}aria-roledescription={roleDescription}aria-disabled={disabled ||undefined}>{#if!pan}<spanclass="cropper-handle cropper-handle-top cropper-handle-left"></span><spanclass="cropper-handle cropper-handle-top"></span><spanclass="cropper-handle cropper-handle-top cropper-handle-right"></span><spanclass="cropper-handle cropper-handle-right"></span><spanclass="cropper-handle cropper-handle-bottom cropper-handle-right"></span><spanclass="cropper-handle cropper-handle-bottom"></span><spanclass="cropper-handle cropper-handle-bottom cropper-handle-left"></span><spanclass="cropper-handle cropper-handle-left"></span>{/if}</div><pclass="cropper-status"role="status"></p></div>{#if pan}{@renderzoom?.({type:'range',min:1,max: maxZoom,step:'any',value: first.zoom??1, disabled,'aria-controls': name })}{/if}
ui/Cropper.vue
<scriptlang="ts">importtype{ Crop }from'@master/ui/behaviors/cropper.js'exporttype{ Crop }/** What the page's range input takes to zoom a panned cropper: bind it on the input. */exportinterfaceCropperZoomAttributes{type:'range'min:numbermax:numberstep:'any'value:numberdisabled?:boolean'aria-controls':string}</script><scriptsetuplang="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:stringalt:string/** The picture's own size, in pixels: the crop is counted in them. */width:numberheight: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)=>stringdisabled?: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()constname=()=>(attrs.idasstring|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 asRef<Crop|null|undefined>,{// The box says change once a gesture or a key has ended.change:(event)=>{if((event.targetasElement).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.constcrop=()=>current()?? first/** A share of the picture as the behavior writes it. */constshare=(part:number)=>String(Math.round(part *1e5)/1e5)constshares=()=>{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><divclass="cropper":class="{'cropper-pan': pan,'cropper-round': round }":style="shares()"ref="root"v-bind="$attrs":id="name()"><imgclass="cropper-image":src="src":alt="alt":width="width":height="height"><divclass="cropper-box"role="application":tabindex="disabled ?-1:0":aria-label="label":aria-roledescription="roleDescription":aria-disabled="disabled ||undefined"><templatev-if="!pan"><spanclass="cropper-handle cropper-handle-top cropper-handle-left" /><spanclass="cropper-handle cropper-handle-top" /><spanclass="cropper-handle cropper-handle-top cropper-handle-right" /><spanclass="cropper-handle cropper-handle-right" /><spanclass="cropper-handle cropper-handle-bottom cropper-handle-right" /><spanclass="cropper-handle cropper-handle-bottom" /><spanclass="cropper-handle cropper-handle-bottom cropper-handle-left" /><spanclass="cropper-handle cropper-handle-left" /></template></div><pclass="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. --><slotv-if="pan"name="zoom"v-bind="{type:'range',min:1,max: maxZoom,step:'any',value:crop().zoom??1, disabled,'aria-controls':name()}asCropperZoomAttributes" /></template>
/* * 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:inset0001pxvar(--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:1pxsolid 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:.5pxsolidvar(--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:inset0001pxvar(--color-on-image),000.5pxvar(--color-on-image-shade),006pxvar(--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:0009999pxvar(--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(toright,transparentcalc(100%/3-.5px),var(--color-on-image)0calc(100%/3+.5px),transparent0calc(200%/3-.5px),var(--color-on-image)0calc(200%/3+.5px),transparent0),linear-gradient(tobottom,transparentcalc(100%/3-.5px),var(--color-on-image)0calc(100%/3+.5px),transparent0calc(200%/3-.5px),var(--color-on-image)0calc(200%/3+.5px),transparent0);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:2pxsolidvar(--color-on-image);outline-offset:2px;box-shadow:inset0001pxvar(--color-on-image),0002pxvar(--color-focus),006pxvar(--color-on-image-shade);}&:focus-visible::after{opacity:.6;}&[aria-disabled="true"]{cursor:default;.cropper-handle{display:none;}}@media(forced-colors:active){outline:2pxsolid 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:000.5pxvar(--color-on-image-shade),01px2px-.5pxvar(--color-on-image-shade),02px6px-1pxvar(--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:0001px 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;}}