background:
Under normal circumstances, there will be no cross-domain problems with pictures, but when I need to do picture gradients, I need to use canvas to obtain the pixels in the picture. At this time, pictures will usually appear cross-domain.
Solution:
- The backend sets the header to *, and the frontend adds the crossOrigin attribute to the image tag as anonymous (IE10 browser does not support crossOrigin)
- Convert the image address into a Blob object through the XMLHttpRequest request, so that there will be no cross-domain problems due to domain names, etc.
method one:
Configure Access-Control-Allow-Origin information for the image server
header("Access-Control-Allow-Origin: *");
// 获取指定图片的域名
header("Access-Control-Allow-Origin: http://......")
Configure the image crossOrigin as anonymous
<img src="http://..." crossOrigin="anonymous">
const image = new Image()
image.src = url
image.crossOrigin = "anonymous"
Method Two:
Instead of requesting pictures through the img tag, get the blob address of the picture indirectly through XMLHttpRequest
const xhr = new XMLHttpRequest()
xhr.onload = function () {
const url_blob = URL.createObjectURL(this.response)
const image = new Image()
image.src = url_blob
image.onload = () => {
// 这里面就可以对图片进行任意操作了
}
}
// url 图片的地址
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.send()
The second method will request the picture twice. Although there is no browser compatibility problem, the picture should not be too large because it is a blob address, otherwise there will be problems if it exceeds the blob size limit.