小程序canvas的API并沒有像其他的一樣支持小程序獨有的 rpx 自適應尺寸單位,在繪制內(nèi)容時所應用的單位仍然是 px,那么如何實現(xiàn)不同尺寸屏幕的自適應呢?
我們的在開發(fā)中常用的參考屏幕尺寸(iPhone6)為:375*667;
那么想要適應其他尺寸的屏幕時只需按照iPhone6的繪制大小按比例進行換算即可:
獲取系統(tǒng)屏幕尺寸
先利用wx.getSystemInfo (獲取系統(tǒng)信息)的API獲取屏幕寬度,然后除iPhone6的屏幕寬度,即可得到相對單位
// 在onLoad中調(diào)用const that = thiswx.getSystemInfo({ success: function (res) { console.log(res) that.setData({ model: res.model, screen_width: res.windowWidth/375, screen_height: res.windowHeight }) }})在繪制方法中將參數(shù)乘以相對單位即可實現(xiàn)自適應
這里的rpx是相對不同屏幕寬度的相對單位,測量出得實際寬度,就是實際測出的px像素值*rpx就可以了;之后無論實在iPhone5,iPhone6,iPhone7...都可以進行自適應。
這里的html也要動態(tài)的設置寬和高
<canvas canvas-id="PosterCanvas" style="width:{{screen_width*375+'px'}}; height:{{screen_height*1.21+'px'}}"></canvas>drawPoster(){ let ctx = wx.createCanvasContext('PosterCanvas'),that=this.data; console.log('手機型號' + that.model,'寬'+that.screen_width*375,'高'+ that.screen_height) let rpx = that.screen_width //這里的rpx是相對不同屏幕寬度的相對單位,實際的寬度測量,就是實際測出的px像素值*rpx就可以了;之后無論實在iPhone5,iPhone6,iPhone7...都可以進行自適應。 ctx.setFillStyle('#1A1A1A') ctx.fillRect(0, 0, rpx * 375, that.screen_height * 1.21) ctx.fillStyle = "#E8CDAA"; ctx.setFontSize(29*rpx) ctx.font = 'normal 400 Source Han Sans CN'; ctx.fillText('Hi 朋友', 133*rpx,66*rpx) ctx.fillText('先領禮品再買車', 84*rpx, 119*rpx) ctx.drawImage('../../img/sell_index5.png', 26*rpx, 185*rpx, 324*rpx, 314*rpx) ctx.drawImage('../../img/post_car2x.png', 66 * rpx, 222 * rpx, 243 * rpx, 145 * rpx) ctx.setFontSize(16*rpx) ctx.font = 'normal 400 Source Han Sans CN'; ctx.fillText('長按掃描獲取更多優(yōu)惠', 108*rpx, 545*rpx) ctx.drawImage('../../img/code_icon2x.png', 68 * rpx, 575 * rpx, 79 * rpx, 79 * rpx) ctx.drawImage('../../img/code2_icon2x.png', 229 * rpx, 575 * rpx, 79 * rpx, 79 * rpx) ctx.setStrokeStyle('#666666') ctx.setLineWidth(1*rpx) ctx.lineTo(187*rpx,602*rpx) ctx.lineTo(187*rpx, 630*rpx) ctx.stroke() ctx.fillStyle = "#fff" ctx.setFontSize(13 * rpx) ctx.fillText('xxx科技汽車銷售公司', 119 * rpx, 663 * rpx) ctx.fillStyle = "#666666" ctx.fillText('朝陽區(qū)·望京xxx科技大廈', 109 * rpx, 689 * rpx) ctx.setFillStyle('#fff') ctx.draw() },保存到相冊
很簡單就是在畫完圖片之后的draw回調(diào)函數(shù)里調(diào)用canvasToTempFilePath()生產(chǎn)一個零時內(nèi)存里的鏈接,然后在調(diào)用
新聞熱點
疑難解答