canvas使用跨域的图片时,image.crossOrigin = 'Anonymous',Tainted canvases may not be exported?

作者站长头像
站长
· 阅读数 5

canvas使用跨域的图片时,不加 image.crossOrigin = 'Anonymous'; 图片可以绘制,但是不能调用 toBlob(), toDataURL() 或 getImageData() 方法,调用它们会抛出安全错误。

Unable to get data URL. Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.

如果加上 image.crossOrigin = 'Anonymous'; 报错 Access to image at 'http://10.10.10.112/product/AVWT-154FESSA.png' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


问题的原因:是后端没有配置允许接受跨域

回复
1个回答
avatar
test
2024-06-25

换下小写试试

image.setAttribute(‘crossorgin’,’anonymous’)

将image作为文件读取blob流,ctx.toBlob 试试

export function imageToFileByCanvas(image: HTMLImageElement, fileName: string = "image.jpg"): Promise<File> {
    const canvas = document.createElement("canvas")
    canvas.width = image.width
    canvas.height = image.height

    const ctx = canvas.getContext("2d")!
    ctx.drawImage(image, 0, 0)

    return new Promise(resolve => canvas.toBlob(blob => resolve(new File([blob!], fileName))))
}

async function getImage(){
      const file = await imageToFileByCanvas(image, "image.jpg")
    const imgUrl = URL.createObjectURL(file) // image 内存地址
}

export function imageToFileByBlob(image: HTMLImageElement, fileName: string = "image.jpg") {
    const binStr = atob(image.src.split(",")[1])
    const len = binStr.length
    const arr = new Uint8Array(len)
    for (let i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i)
    }

    const blob = new Blob([arr], { type: "image/png" })
    return new File([blob], fileName)
}

stackoverflow

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容