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


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

微信小程序Canvas接口函數








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

微信小程序畫圖實例

基本步驟

wxml中代碼:

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

js中onLoad()函數

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

路徑的畫法:

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按鈕,因此需解決該問題。

解決方案

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

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;" />

效果展示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM