<!-- 标签是在组件当中使用,组件和页面使用是有区别的 --> <canvas style="width:{{imgWidth}}px;height:{{imgHeight}};position:fixed;left:9999px" type="2d" id="myCanvas" class="canvas"></canvas> // 下载静态码 myCanvas是我的背景图片 // 这里的处理,调用this.getQRCodeImg生成二维码图片再绘制背景图片 handleDownload() { this.getQRCodeImg().then(data=> { wx.createSelectorQuery().in(this).select('#myCanvas').fields({ node: true, size: true, }) .exec( async res=> { const canvas = res[0].node const width = res[0].width this.canvasWidth = width const height = res[0].height this.canvasHeight = height const ctx = canvas.getContext('2d') const dpr = wx.getSystemInfoSync().pixelRatio canvas.width = res[0].width * dpr canvas.height = res[0].height * dpr ctx.scale(dpr, dpr) ctx.clearRect(0, 0, wx.getSystemInfoSync().windowWidth, wx.getSystemInfoSync().windowHeight) const img = canvas.createImage() img.src = '../../image/back-img.png' // 可以是本地地址也可以是网络地址 let imgHeight = null wx.getImageInfo({ src:'../../image/back-img.png', success(res){ // 屏幕宽度/图片宽度 * 图片高度 imgHeight = wx.getSystemInfoSync().windowWidth/res.width * res.height console.log(res); } }) img.onload = () => ctx.drawImage(img, 0, 0, wx.getSystemInfoSync().windowWidth, imgHeight) const codeImg = canvas.createImage() codeImg.src = data // 可以是本地地址也可以是网络地址 wx.getImageInfo({ src:data, success(res){ // console.log(res); } }) codeImg.onload = () => ctx.drawImage(codeImg, codePosition, 146, 151, 151) wx.showModal({ title: '提示', content: '是否下载图片??', success: (res)=> { if (res.confirm) { wx.canvasToTempFilePath({ canvas: canvas, success: (res) => { // console.log(resx.tempFilePath); wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: function (data) { wx.showToast({ title: '已保存到相册', icon: 'success', duration: 2000 }) }, fail: function (err) { }, complete(res) { wx.hideLoading(); console.log(res); } }) }, fail: (ex) => { console.log(ex); } },this); } } }) }) }) }, // 生成图片 staticCode是我的另外一个Canvas它是一个二维码 getQRCodeImg() { const ctx = wx.createCanvasContext('staticCode') return new Promise((resolve,rejects)=> { setTimeout(() => { ctx.draw(false, setTimeout(() => { wx.canvasToTempFilePath({ width: codewidth, height: codewidth, canvasId: 'staticCode', success: res => { resolve(res.tempFilePath) }, fail: error => { rejects(error) } }, this) },300)) }, 200) }) },
标签:canvas,const,success,res,ctx,2d,type,wx From: https://www.cnblogs.com/tangyuqi/p/16924390.html