小程序畫布創(chuàng)建離屏canvas實(shí)例wx.createOffscreenCanvas
OffscreenCanvas wx.createOffscreenCanvas(object object, number width, number height, Object this)
創(chuàng)建離屏 canvas 實(shí)例
基礎(chǔ)庫 2.16.1 開始支持,低版本需做兼容處理。
小程序插件:支持,需要小程序基礎(chǔ)庫版本不低于 2.16.1
微信 Windows 版:支持
微信 Mac 版:支持
參數(shù)
object object
屬性 類型 默認(rèn)值 必填 說明
type string webgl 否 創(chuàng)建的離屏 canvas 類型
合法值 說明
webgl webgl類型上下文
2d 2d類型上下文
width number 否 畫布寬度
height number 否 畫布高度
compInst Component 否 在自定義組件下,當(dāng)前組件實(shí)例的 this
返回值
OffscreenCanvas
示例代碼
// 創(chuàng)建離屏 2D canvas 實(shí)例
const canvas = wx.createOffscreenCanvas({type: '2d', width: 300, height: 150})
// 獲取 context。注意這里必須要與創(chuàng)建時(shí)的 type 一致
const context = canvas.getContext('2d')
// 創(chuàng)建一個(gè)圖片
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)
// 獲取畫完后的數(shù)據(jù)
const imgData = context.getImageData(0, 0, 300, 150)
作者:大學(xué)生新聞網(wǎng) 來源:大學(xué)生新聞網(wǎng)
發(fā)布時(shí)間:2025-04-10 閱讀: