問題描述:将網絡照片傳給vue-cropper時,報跨域問題,導緻圖檔無法顯示
解決方案:前提條件 圖檔伺服器允許跨域
1 擷取網絡照片位址
getImgUrl(url, showFodder) {
if (url) {
this.setImgBase64(url, base64 => {
this.$nextTick(() => {
this.showFodder.status = showFodder.status
const index = showFodder.index
// 提取size
const fitmentIndex = this.productOption.fitmentIndex
let tempArr = this.productTempArr[fitmentIndex]
let tempIndex = this.productOption.indexArr[fitmentIndex].index
let temp = tempArr[tempIndex]
let module = temp.module[index]
if (module.code) {
let size = []
size.push(module.code.width)
size.push(module.code.height)
this.showFodder.size = size
this.showFodder.autoCropWidth = size[0]
this.showFodder.autoCropHeight = size[1]
this.showFodder.url = base64
if (this.showFodder.url) {
this.showFodder.cropper = true
}
}
})
})
}
},
2 設定需要展示的圖檔,将圖檔轉為base64,否則報跨域問題,我之前就是因為這個原因報的跨域
// 将網絡圖檔轉換成base64格式
transBase64FromImage(image) {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
// 可選其他值 image/jpeg
return canvas.toDataURL('image/jpeg')
},
// 設定需要展示的圖檔 base64
setImgBase64(src, callback) {
let _this = this
let image = new Image()
// 處理緩存
image.src = src + '?v=' + Math.random()
// 支援跨域圖檔
image.crossOrigin = '*'
image.onload = function() {
let base64 = _this.transBase64FromImage(image)
callback && callback(base64)
}
},
3 顯示裁剪框,開始裁剪并擷取裁剪後的照片位址
// 擷取裁剪圖檔
getCropperInfo(url, showFodder) {
if (url) {
const index = parseInt(showFodder.index)
// 目前操作子產品
const fitmentIndex = this.productOption.fitmentIndex
let tempArr = this.productTempArr[fitmentIndex]
let tempIndex = this.productOption.indexArr[fitmentIndex].index
let temp = tempArr[tempIndex]
let module = temp.module[index]
module.code.img = url
temp.module.splice(index, 1, module)
this.initProduct()
}
},
4 把資料送出到伺服器
參考位址:https://blog.csdn.net/Ton555555/article/details/111337934