canvas跨域:Tainted canvases may not be exported解决方法

现象:

  使用html2canvas.js插件绘图时跨域图片绘制过程中报错:Tainted canvases may not be exported

解决方法:

  var content = document.getElementById("theme"+index);
          var w = content.offsetWidth;
          var h = content.offsetHeight;
          
        html2canvas($("#theme"+index)[0], {
            width : w,
            height : h,
            scale : 2,//图片放大倍数
            tainttest : true, //检测每张图片都已经加载完成
            useCORS : true,//使用跨域(当allowTaint为true时这段代码没什么用)
            logging : true,//开启日志
        }).then(function(canvas) {
            var dataUrl = canvas.toDataURL();
            $("#targetimg").attr("src",dataUrl);
            $("#theme"+index).hide();
        });

这里解释一下useCORS没有起作用的原因:
} else if ( isSameOrigin( src ) || options.allowTaint ===  true ) {

} else if ( supportCORS && !options.allowTaint && options.useCORS ) {

};

这里我们看到这两个判断是互相矛盾的options.allowTaint为true那么!options.allowTaint永远为false。

说明:

  关于html2canvas.js,如果绘制的图片长度不超过屏幕宽度,建议使用最新的html2canvas.js版本,傻瓜模式绘图功能强大,比之前的旧版本好多了。下载地址为:https://github.com/niklasvh/html2canvas/releases

发布了27 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/dragon974539495/article/details/89711260