공식 홈페이지 - Cropper.js
GitHub 주소 - GitHub - fengyuanchen/cropperjs: JavaScript image cropper.
JavaScript의 Container와 Canvas 기능을 활용한 오픈소스로 Canvas 안 이미지를 자유롭게 편집하고 Canvas를 이미지 파일로 쉽게 저장할 수 있도록 도와준다.
라이선스 : MIT
<!-- Wrap the image or canvas element with a block element (container) -->
<div>
<img id="image" src="picture.jpg">
</div>
/* Ensure the size of the image fit the container perfectly */
img {
display: block;
/* This rule is very important, please don't ignore this */
max-width: 100%;
}
// import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
},
});
https://github.com/fengyuanchen/cropperjs/raw/master/docs/images/layers.jpg
https://github.com/fengyuanchen/cropperjs/raw/master/docs/images/data.jpg
new Cropper(image, options)
Cropper.setDefualts(options)
viewMode
dragMode
preview
restore
checkCrossOrigin
autoCropArea
zoomOnWheel
cropBoxResizeable
toggleDragModeOnDbclick
getData()
getContainerData()
getImageData()
getCanvasData()
getCropBoxData()
getCroppedCanvas([options])
ready
cropstart
cropmove
cropend
Canvas
-> blob
Blob
-> FormData
로 넘기기FormData
에서 서버로 넘기기//1. 기본 형식
cropper.getCroppedCanvas();
//2. Options사용 방식
cropper.getCroppedCanvas({
width: 160,
height: 90,
minWidth: 256,
minHeight: 256,
maxWidth: 4096,
maxHeight: 4096,
fillColor: '#fff',//투명도 설정 가능
imageSmoothingEnabled: false,
imageSmoothingQuality: 'high',
});
//3. 서버에 올릴 수 있도록 파일로 변환하는 방법
cropper.getCroppedCanvas().toBlob((blob) => {
//HTMLCanvasElement를 return 받아서 blob파일로 변환해준다
const formData = new FormData();
formData.append('croppedImage', blob/*, 'example.png' , 0.7*/);
//새로운 formData를 생성해서 앞에서 변경해준 blob파일을 삽입한다.(이름 지정 가능, 맨뒤 매개변수는 화질 설정)
// jQuery.ajax이용해서 서버에 업로드
$.ajax('/path/to/upload', {
method: 'POST',
data: formData,//앞에서 생성한 formData
processData : false, // data 파라미터 강제 string 변환 방지
contentType : false, // application/x-www-form-urlencoded; 방지
success() {
console.log('Upload success');
},
error() {
console.log('Upload error');
},
});
}/*, 'image/png' */);//서버에 저장 형식 사용 가능
png 저장을 추천드립니다.
사용자 요구에 맞게 오픈소스 변경하기 위해 CDN 방식을 미 사용