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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| <view class="cantainer"> <canvas id="Canvasbg" type="2d" style=" width: 100%; height: 100vh;" class="poster"/> <!-- <canvas id="myCanvas" type="2d" style="border: 1px solid; width: 300px; height: 150px;" /> --> <view class="cantainer-bottom"> <view class="info"> <text >图片已生成,保存发布出来让朋友点赞吧!</text> </view> <button class="btn" size="default" bind:tap="saveImage">保存</button> </view> </view>
.cantainer{ display: flex; flex-direction: column; flex-grow: 1; background-color: skyblue; height: inherit; &-bottom { display: flex; flex-direction: column; height: 600rpx; background-color: white; justify-content: center; align-items: center;
.info { height: 100rpx; font-size: 32rpx; line-height: 32rpx; } .btn{ background-color: var(--primary-color); width: 240rpx; height: 80rpx; color: white; border-radius: 40rpx; } } }
data: { photo:"../../../asset/squase.jpg", imgUrl:"../../../asset/squase.jpg", name: 'demo', desc: '一个海报的demo', address: '小行星', canvas:'', }, onReady() { this.draw() }, draw() { wx.createSelectorQuery() .select('#Canvasbg') .fields({ node: true ,size: true}) .exec((res) => { const canvas = res[0].node const ctx = canvas.getContext('2d') const dpr = wx.getSystemInfoSync().pixelRatio const width = res[0].width const height = res[0].height canvas.width = width * dpr canvas.height = height * dpr ctx.clearRect(0, 0, width, height) ctx.save() ctx.fillStyle= 'white' ctx.fillRect(150,200,800,1000) ctx.restore() let img = canvas.createImage() img.src= this.data.imgUrl img.onload =() =>{ ctx.save() ctx.beginPath() ctx.rect(150,200,800,1000) ctx.clip() ctx.drawImage(img,0,150,1000,550) ctx.closePath() ctx.restore() } ctx.font="40px Arial" ctx.fillText(`N A M E: ${this.data.name}`,200,900) ctx.fillText(`A D D R E S S: ${this.data.address}`,200,980) ctx.fillText(`D E S C R I P T I O N: ${this.data.desc}`,200,1060) let photo = canvas.createImage() photo.src= this.data.photo photo.onload = () => { ctx.save() ctx.beginPath() ctx.arc(830,900,100,0,2 * Math.PI) ctx.clip() ctx.drawImage(photo,710,800,400,400) ctx.closePath() ctx.restore() } this.setData({ canvas }) }) }, saveImage() { const canvas = this.data wx.showLoading({title:'海报生成中...'}), wx.canvasToTempFilePath({ canvas, success: res => { const tempFilePath = res.tempFilePath wx.hideLoading() }, fail: err => { wx.hideLoading() console.log('保存失败,请重试!',err) } }) }
|