uniapp/小程序实现canvas画布保存图片
<template> <view> <canvas canvas-id="gameCanvas" style="width:750rpx; height:1232rpx;"></canvas> </view> </template>
<script> export default { data() { return { kehu: '', pingming: '', date: '', zhongliang: '', zongjine: '' }; }, onLoad(options) { const ctx = uni.createCanvasContext('gameCanvas'); //创建画布对象 uni.showLoading({ title: '正在生成中...' }) console.log(options) //接收上个页面的数据 this.kehu = options.buyerOrg; this.pingming = options.goodsName; this.zhongliang = options.settleWeight; this.date = options.createTime; this.zongjine = options.settlement; let imageWidth = 375, imageHeight = 616; uni.getImageInfo({ src: 'https://xxxxxxxxxxxxxxxxxx.png', //网络图片用来做背景 success: (res) => { console.log(res.path) ctx.save() ctx.drawImage(res.path, 0, 0, 375, 616) ctx.draw(true) ctx.setFillStyle('#333333') ctx.draw(true) ctx.setFillStyle('black') ctx.setFontSize(16) ctx.fillText('客户名:' + this.kehu, 30, 130) ctx.fillText('品名:' + this.pingming, 30, 190) ctx.fillText('重量:' + this.zhongliang + '吨', 30, 250) ctx.fillText('总金额:' + '¥' + this.zongjine, 30, 310) ctx.fillText('日期:' + this.date, 30, 370) ctx.draw(true) setTimeout(() => { //解决画布空白的问题 ctx.draw(true, () => { // console.log(666) uni.canvasToTempFilePath({ //将canvas生成图片 canvasId: 'gameCanvas', x: 0, y: 0, width: imageWidth, height: imageHeight, destWidth: imageWidth, //截取canvas的宽度 destHeight: imageHeight, //截取canvas的高度 success: function(res) { uni.saveImageToPhotosAlbum({ //保存图片到相册 filePath: res.tempFilePath, success: function() { uni.hideLoading() uni.showToast({ title: "图片已保存", duration: 2000 }) }, fail() { uni.hideLoading() } }) } }) }) }, 1500); } }) }, } </script>
再忙也别忘记学习