介紹
cropperjs是一款基於JavaScript的網頁端圖片裁剪插件,可能相對於圖片預覽來說,圖片的裁剪使用場景貌似並不是很多,但是圖片預覽插件又要比裁剪插件容易找到,而且從實現難度上來說也不及圖片裁剪,今天我們就一起來看看這款良心的圖片裁剪插件——Cropperjs
Github
作者的幾個經典作品都在Github上,並且都獲得不菲的stars,感謝作者提供這麼好用的免費插件
https://github.com/fengyuanchen/cropperjs
特性
安裝
使用npm安裝或者直接下載編譯好的js文件
npm install cropperjs
使用
- 語法
new Cropper(element[, options])
- 類型:HTMLImageElement或HTMLCanvasElement
- 用於裁剪的目標圖像或畫布元素。
- 類型: Object裁剪配置選項。
使用案例:

img {
display: block;
/* This rule is very important, please don't ignore this */
max-width: 100%;
}
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);
},
});
PS:具體的配置選項可以到Github上查看相關文檔,同時也提供了一個在線的預覽demo
在線預覽Demo
https://fengyuanchen.github.io/cropperjs/
總結
cropperjs是一個純前端的圖片裁剪工具,同時筆者之前文章也介紹過和cropperjs同源作者的另一個佳作viewerjs,這是一個優秀的前端圖片預覽插件,功能豐富,配置簡單,推薦使用,enjoy it!
文章來源: https://twgreatdaily.com/UpFSBHEBiuFnsJQVp-ou.htmlhttps://www.toutiao.com/i6775436136027259404/