uniapp-vue2-微信小程序,canvas 裁切图片的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | <canvas class = "edit-question-canvas" type= "2d" id= "canvasCuteImage" ></canvas> /* .edit-question-canvas { position: absolute; left: -750rpx; width: 690rpx; height: 100rpx; } 样式随便自己写 */ // 使用方法 let path = await this .canvasCuteImageExecute(item.data.path, 690, item.data.rect, '#canvasCuteImage' , this .pxRatio) /* path:本地图片的地址 w: 截取后图片的宽度 rect:[x,y,width,height] 解决的矩形范围 canvasId:canvas id pxRatio:rpx 转 px 的比例 onLoad() { let that = this uni.getSystemInfo({ success: function(res) { that.pxRatio = res.windowWidth / 750 } }) }, */ canvasCuteImageExecute(path, w, rect, canvasId, pxRatio) { return new Promise((resolve, reject) => { let canvasHeight = Math.floor(w * rect[3] / rect[2]) let x = rect[0] let y = rect[1] let width = rect[2] let height = rect[3] let destWidth = w * pxRatio let destHeight = canvasHeight * pxRatio const query = wx.createSelectorQuery() query.select(canvasId) .fields({ node: true , size: true }) .exec((res) => { const canvas = res[0].node const ctx = canvas.getContext( '2d' ) canvas.width = destWidth canvas.height = destHeight let image = canvas.createImage(); //创建image实例 image.src = path image.onload = function () { ctx.drawImage(image, x, y, width, height, 0, 0, destWidth, destHeight); wx.canvasToTempFilePath({ canvas: canvas, success(res) { // console.log(res.tempFilePath); resolve(res.tempFilePath) }, fail(err) { console.log(err) resolve( '' ) } }) } }) }) // 计算 canvas 的高度 }, |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通