1、在線圖片資源跨域的問題
解決方法:將“跨域圖片資源”轉換成base64后,用base64渲染img標簽,這樣完美解決問題;
如何將“跨域圖片”轉換成base64呢?原理很簡單,將img繪制成canvas,再將canvas轉換成base64的img流;
因為圖片是跨域的,所以我們在轉換過程中需要加一段代碼:image.crossOrigin = "*";,用來處理跨域;
let image = new Image() image.src = this.networkImg image.crossOrigin = "*"
發現偶爾還是會報錯:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
2、圖片url緩存
在這里能找到答案:https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osx
If your images come from a different domain, and you want to be able to export the canvas content after you did draw these images, then you have no choice than loading them with the
crossOrigin
attribute.If you are really facing the linked bug, according to it, the proper fix is to always send the CORS headers from your server response, whether or not the request is made with the Origin header.
And a fast workaround is to avoid the cache, by appending a random query string in the image's src (
img.src = url + '?v=' + Math.random();
).
需要加個隨機數防止緩存即可
let image = new Image() image.src = this.networkImg + '?v=' + Math.random() image.crossOrigin = "*"
我代碼里的解決
insertImg () { let _this = this let image = new Image() image.src = this.networkImg + '?v=' + Math.random() image.crossOrigin = "*" image.onload = function(){ let base64 = _this.getBase64Image(image) _this.talkInfo.imageUrls.push(base64) _this.networkImg = '' } }, getBase64Image (img) { let canvas = document.createElement("canvas") canvas.width = img.width canvas.height = img.height let ctx = canvas.getContext("2d") ctx.drawImage(img, 0, 0, img.width, img.height) let dataURL = canvas.toDataURL("image/png") return dataURL },
思路:
1、image的onload下載圖片資源
2、利用canvas轉換base64
3、避免跨域及緩存的坑