使用canvas 的 toDataUrl方法会遇到跨域问题
chrome 会报下面的错误:
Uncaught SecurityError: Failed to execute ‘toDataURL‘ on ‘HTMLCanvasElement‘: Tainted canvases may not be exported.
Firefox 会报下面的错误:
SecurityError: The operation is insecure.
解决方案分两步:
1、在服务端设置响应头部
Access-Control-Allow-Origin: *
2、js设置image crossOrigin 为 Anonymous
image.crossOrigin = "Anonymous"; image.onload = function(){ context.drawImage(this, 0, 0, 400, 300); var base64Url = canvas.toDataURL("image/png"); console.log(base64Url); }; image.src = imageSrc;
时间: 2024-08-03 22:38:18