微信小程序canvas轉圖片臨時路徑,使用wx.canvasToTempFilePath方法,官方文檔中寫了要在 draw() 回調里調用該方法才能保證圖片導出成功。
然而,顯示是寫在draw()里面會報錯draw is not a function,查閱了一下資料,新版 Canvas 2D 接口與 Web 一致,是沒有 draw 方法的。https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.html
所以調wx.canvasToTempFilePath時不用寫在draw里面,wx.canvasToTempFilePath的canvas參數(shù)的值不是canvas id了,而是canvas實例
參考代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-511038.html
rotatePic() {
let that = this
//獲取canvas
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec(function(res) {
const canvas = res[0].node
canvas.width = that.canvasWidth
canvas.height = that.canvasHeight
const ctx = canvas.getContext('2d')
const bg = canvas.createImage()
bg.src = that.imgUrl
bg.onload = () => {
//先保存一下設置
ctx.save();
//將畫布向右下移動一半寬
ctx.translate(canvas.width / 2, canvas.height / 2);
//再旋轉角度:逆時針旋轉180度
ctx.rotate(-180 / 180 * Math.PI);
//最后將畫布移回來,擺正之前的位置
ctx.translate(-canvas.width / 2, -canvas.height / 2);
//最后畫出來
ctx.drawImage(bg, 0, 0);
//不要忘記恢復之前的設置
ctx.restore()
//canvas轉文件的臨時路徑 (本地路徑)
wx.canvasToTempFilePath({
canvas,
fileType: "jpg",
quality: 1,
success: (res) => {
that.imgUrl = res.tempFilePath//這個就是要的路徑了
}
})
}
})
}
參考文章:如何解決draw()報錯 ctx.draw is not a function 的問題?文章來源地址http://www.zghlxwxcb.cn/news/detail-511038.html
到了這里,關于微信小程序wx.canvasToTempFilePath,draw()報錯 ctx.draw is not a function的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!