uniapp 生成海报自适应

html部分
生成海报 长按可保存海报
js部分
data() {return {width: 0,height:0}},methods: {//生成海报generatePoster() {let that=this//计算图片尺寸uni.getImageInfo({src: req.data.poster.image.url,success: function (image) {let height = 200;let allwh = image.width + image.height;let imgwidth = (image.width / allwh).toFixed(2);let imgheight = (image.height / allwh).toFixed(2);that.width = imgwidth*1000;that.height = (imgheight*1000) + height;// 这里是创建 canvas 绘图上下文let context = uni.createCanvasContext('myCanvas');// 这里可以根据自己的需求显示加载动画uni.showToast({title: '正在生成海报,请稍后...',icon: 'none',duration: 3000});// 给整个canvas填充白色背景(这个如果不加上的话,在APP端生成的海报没有白色背景)context.setFillStyle('#ffffff');context.fillRect(0, 0,500, that.height);context.draw();// 绘制用户昵称context.setFontSize(14);context.setFillStyle('#000000');// 这里根据自己的项目填写用户昵称的字段//let user = uni.getStorageSync('user')context.fillText('昵称', 100, 48);context.setFontSize(12);context.setFillStyle('#82848a');context.fillText('早上好!!这是您专属', 100, 68);// 绘制价格// context.setFontSize(18);// context.setFillStyle('red');// context.fillText(`¥199`, 20, 366);// // 绘制商品名称,按字符串长度进行分割换行。that.drawText('描述....', 20, that.height+120-height, context);that.drawText('长按识别二维码', 20, that.height+160-height, context);// 绘制头像uni.downloadFile({url: '', //用户的头像地址(一定要是网络路径)success: function(res) {context.save();// 这个就是绘制圆形头像context.beginPath();context.arc(50, 50, 30, 0, 2 * Math.PI)context.clip();context.drawImage(res.tempFilePath, 20, 20, 60, 60);context.restore();context.draw(true);}});// 绘制图片详情uni.downloadFile({url: '', //分享图片网络地址success: function(res) {context.drawImage(res.tempFilePath, 2, 92, that.width, that.height-height);context.draw(true);}});// 绘制小程序码uni.downloadFile({url: '',//二维码图片网络地址success: function(res) {context.drawImage(res.tempFilePath, 165, that.height+100-height, 100, 100);context.draw(true);}});// 绘制完成,让canvas显示【这里看自己项目,是否有loading动画】that.posterInfo.status = true;}});},// 海报描述文字换行drawText(context, x, y, canvas) {let strArr = [];let n = 11;for (let i = 0, l = context.length; i < l / n; i++) {let a = context.slice(n * i, n * (i + 1));strArr.push(a);}strArr.forEach((item, index) => {// 限制只能显示4行文字if (index > 3) {return;}y += 20;canvas.setFontSize(12);canvas.setFillStyle('#333333');canvas.fillText(item, x, y);});},// 长按保存生成的海报saveSharePic() {uni.showModal({title: '提示',content: '保存海报分享给好友 o(∩_∩)o',success: function(res) {if (res.confirm) {// canvas生成图片uni.canvasToTempFilePath({// 这里修改保存的图片格式fileType: 'jpg',canvasId: 'myCanvas',quality: 1,success: function(res) {// 保存带哦本地uni.saveImageToPhotosAlbum({filePath: res.tempFilePath,success: function() {uni.showToast({title: '保存海报成功',icon: 'none',duration: 3000});},fail: function() {uni.showToast({title: '保存海报失败',icon: 'none',duration: 3000});}});}});}}});}}
css部分
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
