小程序畫布創建離屏canvas實例wx.createOffscreenCanvas
OffscreenCanvas wx.createOffscreenCanvas(object object, number width, number height, Object this)
創建離屏 canvas 實例
基礎庫 2.16.1 開始支持,低版本需做兼容處理。
小程序插件:支持,需要小程序基礎庫版本不低于 2.16.1
微信 Windows 版:支持
微信 Mac 版:支持
參數
object object
屬性 類型 默認值 必填 說明
type string webgl 否 創建的離屏 canvas 類型
合法值 說明
webgl webgl類型上下文
2d 2d類型上下文
width number 否 畫布寬度
height number 否 畫布高度
compInst Component 否 在自定義組件下,當前組件實例的 this
返回值
OffscreenCanvas
示例代碼
// 創建離屏 2D canvas 實例
const canvas = wx.createOffscreenCanvas({type: '2d', width: 300, height: 150})
// 獲取 context。注意這里必須要與創建時的 type 一致
const context = canvas.getContext('2d')
// 創建一個圖片
const image = canvas.createImage()
// 等待圖片加載
await new Promise(resolve => {
image.onload = resolve
image.src = IMAGE_URL // 要加載的圖片 url
})
// 把圖片畫到離屏 canvas 上
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0, 300, 150)
// 獲取畫完后的數據
const imgData = context.getImageData(0, 0, 300, 150)