需求:APP上传手机原有的图片,进行覆盖指定的部分,覆盖完成后,唤起原生系统的分享面板,面板上有分享给其他人,还有打印选项
准备一个canvas和button标签
<canvas canvas-id="myCanvas" :style="{ width: canvasW + 'px', height: canvasH + 'px' }"/>
<button type="default" @click="clipImg">选择图片</button>
这个canvas主要是把选择的图片画上去,所以不知道选的是哪张图片,当然也不知道宽高是多少,所以用的是动态的宽高,这个宽高一定要设置!!!
完成事件
// 选择图片进行裁剪clipImg() {uni.chooseImage({count: 1, //默认9sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有sourceType: ['album'], //从相册选择success: (success) => {console.log("选择成功后==", success)// this.bgImg = success.tempFilePaths[0]uni.getImageInfo({src: success.tempFilePaths[0],success: info => {console.log("图片信息==", info)const {width,height} = info// 给画布设置宽高this.canvasW = width;this.canvasH = height;// 创建画布const ctx = uni.createCanvasContext('myCanvas');console.log("宽高===", this.canvasW, this.canvasH)// 绘制上传的图片ctx.drawImage(success.tempFilePaths[0], 0, 0, width, height, 0, 0, width, height)// 绘制覆盖层ctx.setFillStyle('white');// 这个是我随便写的一个位置和覆盖的宽高,根据自己的需求来定ctx.fillRect(75,147, width-150, 160)ctx.draw(false, () => {// 将画布内容导出为图片uni.canvasToTempFilePath({canvasId: 'myCanvas',x: 0,y: 0,width: width,height: height,destWidth: width,destHeight: height,success: toTempFilePathRes => {console.log('裁剪后的图片路径:',toTempFilePathRes.tempFilePath);// 处理裁剪后的图片,例如上传或显示// 分享图片plus.share.sendWithSystem({pictures: [toTempFilePathRes.tempFilePath], // 图片路径shareWithSystem: true // 使用系统分享,是因为不仅可以分享给其他人,也可以选择系统自带的打印功能}, function() {console.log("图片分享成功");uni.showToast({title: "图片分享成功!",duration: 1000});}, function(error) {console.error("图片分享失败: " + JSON.stringify(error));uni.showToast({icon: 'none',title: JSON.stringify(error),duration: 1000})});},fail: err => {console.error('导出图片失败:', err);}})})},fail: err => {console.error('获取图片信息失败:', err);}})}});},
canvas绘画API
呼起手机os的系统分享菜单