问题描述:将网络照片传给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