上傳圖片到圖片服務器,因為域名不同,多以會有跨域問題。
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://img.xxx.com' is therefore not allowed access.
照看代碼發現,cropper.js里面對圖片的引用路徑做了判斷,給img標簽添加了 crossorigin="anonymous"(匿名跨域屬性)。
並且用了XMLHttpRequest 的get請求去訪問img的引用路徑,這樣確實訪問不到。需要在圖片服務器,或者返回的請求頭添加 Access-Control-Allow-Origin:*,或Access-Control-Allow-Origin:請求來源域名。
有一種簡單快速的解決辦法,就是直接去掉cropper.js里面跨域屬性,因為默認情況下圖片跨域也是可以顯示的。
對於低版本的cropper.js可以這樣:
this.$clone = $clone = $('<img>'); $clone.one('load', $.proxy(function () { var naturalWidth = $clone.prop('naturalWidth') || $clone.width(), naturalHeight = $clone.prop('naturalHeight') || $clone.height(); this.image = { naturalWidth: naturalWidth, naturalHeight: naturalHeight, aspectRatio: naturalWidth / naturalHeight, rotate: 0 }; this.url = url; this.ready = true; this.build(); }, this)).one('error', function () { $clone.remove(); }).attr({ // crossOrigin: crossOrigin, // "crossOrigin" must before "src" (#271) src: bustCacheUrl || url });
注釋掉那行crossOrigin就好了。
對於高版本(我用的Cropper v2.3.4)因為代碼調整了,找到 function getCrossOrigin(crossOrigin),將里面返回跨域代碼的那行注釋掉,返回空字符串就好了。
我是這樣改的:
function getCrossOrigin(crossOrigin) { //return crossOrigin ? ' crossOrigin="' + crossOrigin + '"' : ''; return ''; }
可以顯示出來了