在 UniApp 中,可以通过 Canvas 或 JavaScript 实现按照长宽比例裁剪图片。以下是具体步骤:
使用 Canvas 裁剪图片Canvas 是 HTML5 提供的绘图工具,适合在前端实现图片裁剪。
实现步骤:获取图片信息:加载图片并获取其原始宽高。计算裁剪区域:根据目标长宽比例计算裁剪区域。绘制到 Canvas:将裁剪后的图片绘制到 Canvas 上。导出裁剪后的图片:将 Canvas 内容导出为图片文件。示例代码:<template> <view> <canvas canvas-id="myCanvas" style="width: 300px; height: 300px;"></canvas> <button @click="cropImage">裁剪图片</button> </view> </template> <script> export default { data() { return { imagePath: '/static/sample.jpg', // 图片路径 targetRatio: 1 / 1, // 目标长宽比例(例如 1:1) }; }, methods: { cropImage() { const ctx = uni.createCanvasContext('myCanvas', this); uni.getImageInfo({ src: this.imagePath, success: (res) => { const imgWidth = res.width; const imgHeight = res.height; const imgRatio = imgWidth / imgHeight; let cropWidth, cropHeight, offsetX, offsetY; if (imgRatio > this.targetRatio) { // 图片宽度过大,按高度裁剪 cropHeight = imgHeight; cropWidth = cropHeight * this.targetRatio; offsetX = (imgWidth - cropWidth) / 2; offsetY = 0; } else { // 图片高度过大,按宽度裁剪 cropWidth = imgWidth; cropHeight = cropWidth / this.targetRatio; offsetX = 0; offsetY = (imgHeight - cropHeight) / 2; } // 绘制裁剪后的图片 ctx.drawImage( this.imagePath, offsetX, offsetY, cropWidth, cropHeight, 0, 0, 300, 300 / this.targetRatio ); ctx.draw(false, () => { // 导出裁剪后的图片 uni.canvasToTempFilePath({ canvasId: 'myCanvas', success: (res) => { console.log('裁剪后的图片路径:', res.tempFilePath); uni.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: () => { uni.showToast({ title: '图片保存成功' }); }, }); }, }); }); }, }); }, }, }; </script>
网友回复