首先說說遇到了什麼問題。首先有這麼一個需求。需要前端根據後端傳過來數據,動態的生成圖。圖片中的文案、背景圖片、使用者頭像全部都是透過後端的介面取得。但是使用html2canvas產生的canvas有些圖片成功的在canvas裡產生了。但有些圖片無論如何都顯示不出來。
官方文檔在專案裡面操作了半天未果,google了半天未果。此時有些許絕望。突然想到了,為什麼不去它的官網看看呢。於是乎我在官網上看到了下面的內容。
Limitations<br/>
All the images that the script uses need to reside under the same origin for it to be able to read them without the assistance of a proxy. Similarly, if you have other canvas elements on the page, which have been tainted with cross-originginia) , they will become dirty and no longer readable by html2canvas.<br/>
The script doesn't render plugin content such as Flash or Java applets.
講的啥呢,這裡為英文不好的同學翻譯一下。英文好的可以直接看上文。大概的意思就是在html2canvas裡面,是使用腳本去操作的,也就是說使用腳本把html轉換成canvas,但有一個限制,就是不能使用跨來源的圖片。如果使用了,html2canvas將不會讀取資源。
這也就是為什麼轉換出來的canvas有些圖片一直是空白的原因。如果頁面中有其他的canvas也使用了跨來源的圖片資源,html2canvas都不會去讀取。
解決方案對靜態資源做一次轉送並且在html2canvas的配置裡面允許載入跨來源資源,就可以了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。