用html2canvas转html为图片遇到的那些问题

1.图片跨域问题

在html转化为canvas在转化成图片地址的 时候 canvas.toDataURL("image/png")

遇到报错:

Access to image at 'png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

或者

Access to image at 'www.baidu.com/GT/github/hotelAdmin/img/tempalte-top.png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

报错原因 就是 图片 跨域 污染了画布,导致画布不能导出img的地址

在网上找方法 

设置:

            useCORS: true, //(图片跨域相关)
            allowTaint: false, //允许跨域(图片跨域相关

$('#div').click(function () {
        html2canvas(template, {
            onrendered: function (canvas) {
              
                    exportCanvasAsPNG(canvas, 'invoice.png')
              
            },
            useCORS: true, //(图片跨域相关)
            allowTaint: false, //允许跨域(图片跨域相关)
            x: 0,
            y: window.pageYOffset,
            windowWidth: document.body.scrollWidth,
            windowHeight: document.body.scrolHeight,
        });
    })

  但是并没有效果

追其根本 是图片跨域的问题

跨域怎么解决

1.设置请求头 

这个需要 图片服务器 那边去设置,这个无法验证是否好用,因为我们服务端说 弄不了这个 所以 pass

2.既然跨域,那我统一域名就可以了 ,再激进一点把文件直接写进代码里

   将图片源码转成blob文件对象,然后用URL.createObjectURL()方法转换成img src可用的地址,然后再绘制在canvas上,在和html一起导出toDataURL,转成图片

怎么做

1.获取图片源码

我这里两张图片是静态图片,不涉及动态,所以 我直接在线转了base64码   在线转base64

2.将跨域的图片转成blob文件对象

    //将base64转换为文件对象
    function dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        //转换成file对象
        // return new File([u8arr], filename, { type: mime });
        //转换成成blob对象
        return new Blob([u8arr], { type: mime });
    }

3.将blob图片对象通过URL.createObjectURL(‘图片blob对象’)转化成图片地址,赋值在img的src上

   $('.top-img').attr('src',URL.createObjectURL(imgfile))
4.进行绘制canvas,此时canvas不会在报错 能够完整绘制整个html
html2canvas(template, {
            onrendered: function (canvas) {
                  
                  var imgURL = canvas.toDataURL( "image/png"); 
这个时候就可以正常执行toDataURL方法了
                   // 导出图片
                    exportCanvasAsPNG(canvas, 'invoice.png')
              
            },
            useCORS: true, //(图片跨域相关)
            allowTaint: false, //允许跨域(图片跨域相关)
            x: 0,
            y: window.pageYOffset,
            windowWidth: document.body.scrollWidth,
            windowHeight: document.body.scrolHeight,
        });

  明天继续写

猜你喜欢

转载自www.cnblogs.com/GoTing/p/12343482.html