在 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> 网友回复
如何让ai帮我自动在小红书或抖音上自动根据需求截流与潜在客户聊天拉客?
如果用go编写一个在virtualbox中启动的简单操作系统?
go如何搭建一个零信任网络?
如何用python实现一个公网代理访问软件?
如何用go实现一个公网代理访问软件?
如何用python实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
如何用go实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
何为Shadowsocks 代理?
python如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?
nodejs如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?


