關於微信小程序前端Canvas組件教程

關於微信小程序前端Canvas組件教程

微信小程序Canvas接口函數








​ 上述爲微信小程序Canvas的內部接口,經過熟練使用Canvas,便可畫出較爲美觀的前端頁面。下面是使用微信小程序畫圖的一些例子。javascript

微信小程序畫圖實例

基本步驟

wxml中代碼:前端

<canvas canvas-id="myCanvas" class="myCanvas" ></canvas>

js中onLoad()函數java

const ctx = wx.createCanvasContext('myCanvas')//建立Canvas
ctx.setFillStyle('green')//選擇填充顏色
ctx.fillRect(10, 10, 150, 75)//形狀描述
ctx.draw()//繪製圖像

路徑的畫法:canvas

const ctx = wx.createCanvasContext('myCanvas')//建立Canvas
ctx.moveTo(10, 10)//初始點選擇
ctx.lineTo(100, 10)//畫線
ctx.lineTo(100, 100)
ctx.fill()//填充形狀
ctx.draw()

文字的畫法:小程序

const ctx = wx.createCanvasContext('myCanvas')
 
ctx.setFontSize(20) //文字大小
ctx.fillText('Hello', 20, 20) //文字後跟的參數爲文字啓示座標
ctx.fillText('MINA', 100, 100)
 
ctx.draw()

圓角矩形的畫法微信小程序

const bot = wx.createCanvasContext('bottcan')

bot.moveTo(0, 0)
bot.lineTo(wid / 2 - 15, 0)
bot.lineTo(wid / 2 + 15, 35)
bot.lineTo(10, 35)
bot.arc(0 + 10, 35 - 10, 10, Math.PI * 0.5, Math.PI)//勾畫圓角矩形的線段
bot.setFillStyle('#FF9955')
bot.fill()
bot.setFillStyle('#414141')
bot.setFontSize(20)
bot.fillText('重填問卷', 50, 25)

按照手機比例畫圖方法

​ 在生成Canvas的時候,須要固定寬度和高度,其中高度比較好固定,可是寬度的固定就比較困難,由於不一樣手機型號寬度不一樣,所以須要得知本機可以使用寬度爲多少。微信

<canvas canvas-id="myCanvas" class="myCanvas"  style = "width:{{windowWidth}}px;height:35px" ></canvas>
var that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth) //獲取用戶手機寬度
        that.setData
          ({
            windowWidth: res.windowWidth * 0.94
          })

      }
    })

    var wid = this.data.windowWidth;

微信小程序層級問題

​ 在微信小程序中,Canvas這種默認組件的層級爲最高,所以在彈出確認與否的提示時,Canva會影響使用,用戶沒法點擊確認或取消,只能點擊Canvas按鈕,所以需解決該問題。函數

解決方案this

​ 在點擊出現選擇框時,將Canvas隱藏,而且生成一張與原始畫布相同的圖片放在該位置,從而達到下降Canvas層級的效果。3d

js代碼:

//radaarImg爲導出的圖片
var that = this
wx.canvasToTempFilePath({
    width: that.data.windowWidth,
    height: 35,
    canvasId: 'myCanvas',
    success: function (res) {
        that.setData({ radarImg: res.tempFilePath });
    }
});

wxml代碼:

<view wx:if = "{{!can1}}">
     <canvas canvas-id="myCanvas" class="myCanvas"  style = "width:{{windowWidth}}px;height:35px" ></canvas>
    </view>
    <image wx:else src="{{radarImg}}" style="width: {{windowWidth}}px; height:35px;" />

效果展現:

相關文章
相關標籤/搜索