一、在線圖片資源跨域的問題canvas
解決方法:將「跨域圖片資源」轉換成base64後,用base64渲染img標籤,這樣完美解決問題;跨域
如何將「跨域圖片」轉換成base64呢?原理很簡單,將img繪製成canvas,再將canvas轉換成base64的img流;緩存
由於圖片是跨域的,因此咱們在轉換過程當中須要加一段代碼:image.crossOrigin = "*";,用來處理跨域;app
let image = new Image() image.src = this.networkImg image.crossOrigin = "*"
發現偶爾仍是會報錯:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.cors
二、圖片url緩存dom
在這裏能找到答案:https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osxpost
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.this
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.url
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();
).spa
須要加個隨機數防止緩存便可
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 },
思路:
一、image的onload下載圖片資源
二、利用canvas轉換base64
三、避免跨域及緩存的坑