uniapp中canvas繪制圖片內容空白報錯的原因及解決

問題圖:

效果圖:

Canvas繪制圖片流程
簡單說一下canvas上繪制圖片的過程
??先調用相機接口拍攝照片,
??把照片URL拿到,
??然后獲取照片URL信息寬高,
??把寬高給畫布,??使用canvas的drawImage API把圖片繪制到canvas上,??繪制方法執(zhí)行完成后把這個canvas導出為圖片,并上傳到服務器,至此流程結束。
首先定義畫布canvas
<canvas class="canvas" canvas-id="canvas"
:style="{ height: canvasHeight + 'px', width: canvasWidth + 'px' }"></canvas>1.畫布的大小大于了圖片的大小導致了生成的內容是空白的
canvas畫布初始值沒有,導致沒有繪制成功
解決:
//默認初始值 canvasWidth1 canvasHeight1
data() {
return {
ctx: null,
canvasWidth: 1080,
canvasHeight: 1440,
}
},2.繪制圖片沒有放到wx.draw方法里面
wx.draw(false, () =>{
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'shareCanvas', // shareCanvas 為制定 繪圖canvas 的ID
success: (res) => {
this.storeImgPath = res.tempFilePath
....寫入生成完成的邏輯
},
complete: (res) => {
wx.hideLoading()
}
})
})3.Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.

canvas無法執(zhí)行toDataURL方法,受污染的畫布無法輸出
受限于CORS 策略,會存在跨域問題,頁面雖然可以使用跨域的圖片(比如使用img標簽或者append到頁面上),因為瀏覽器本身不會有跨域問題,但是一旦繪制到canvas上就會污染這個canvas,導致無法提取到這個canvas的數(shù)據,也就無法輸出了。
上面的都加了還存在,必殺技,延遲方法:
//萬能代碼,不能用你回來找我,能用可以雙擊點贊評論666
console.log('正在繪制')
this.ctx.draw(false,(()=> {
setTimeout(() => {
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: this.canvasWidth1,
height: this.canvasHeight1,
destWidth: this.canvasWidth1,
destHeight: this.canvasHeight1,
canvasId: 'myCanvas',quality:0.6,
success: res => {
// 在H5平臺下,tempFilePath 為 base64
console.log(res,'繪制完成===',)
//上傳
uni.uploadFile({
url: url, //僅為示例,非真實的接口地址
filePath:res.tempFilePath,
header: {
'token': self.$store.state.token,"version":"100.0.00"
},
name: 'file',
formData: {},
success: (uploadFileRes) => {
console.log('uploadFileRes===1111',uploadFileRes)
uni.hideLoading()
},
fail(err) {
console.log(err)
uni.hideLoading()
}
});
// this.pictureArr.push(res.tempFilePath);
},
fail(err) {
console.log(err)
uni.showToast({
title:'上傳圖片失敗!',icon:'none',
duration: 3000
})
uni.hideLoading()
}
}, this)
}, 3500)
})());萬能代碼,不能用你回來找我
總結
到此這篇關于uniapp中canvas繪制圖片內容空白報錯的原因及解決的文章就介紹到這了,更多相關uniapp canvas繪制圖片內容空白內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

