首页 > 其他分享 >解决在Vue3中html2canvas图片跨域问题

解决在Vue3中html2canvas图片跨域问题

时间:2022-11-23 10:38:21浏览次数:44  
标签:canvas const 跨域 contentWidth ctx html2canvas Vue3 pdf

 <div v-html="transformImg(textContent.policyInterpretation)" class="topicContent"></div>

  

const transformImg = (str) =>
{ const replaceCallback = (m, g1) => { return `<img crossOrigin = "anonymous" src=${g1}&t=${Math.random()}>`; }
const srcRes = str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, replaceCallback); return srcRes }

  

const exportPDF = () => {
    const ele: any = document.getElementById("main-charts");
    html2canvas(ele as HTMLElement, {
        scale: 2, // 设置缩放  提升画质
        useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,  这个是解决跨域问题
        logging: false, // 打印日志用的 可以不加默认为false
        width: ele.offsetWidth,
        height: ele.offsetHeight,

    }).then((canvas) => {


        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        // 一页pdf显示html页面生成的canvas高度;
        const pageHeight = (contentWidth / 592.28) * 841.89;
        // 未生成pdf的html页面高度
        let leftHeight = contentHeight;
        // 页面偏移
        let position = 0;
        // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        const imgWidth = 595.28;
        const imgHeight = (595.28 / contentWidth) * contentHeight;
        const ctx: any = canvas.getContext("2d");

        // 添加水印
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.rotate((25 * Math.PI) / 180);
        ctx.font = "20px Microsoft Yahei";
        ctx.fillStyle = "rgba(184, 184, 184, 0.8)";
        for (let i = contentWidth * -1; i < contentWidth; i += 240) {
            for (let j = contentHeight * -1; j < contentHeight; j += 100) {
                // 填充文字,x 间距, y 间距
                ctx.fillText("", i, j);
            }
        }
        const pageData = canvas.toDataURL("image/jpeg", 1.0);
        const pdf = new jsPDF("p", "pt", "a4");
        if (leftHeight < pageHeight) {
            // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
            pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
        } else {
            // 分页
            while (leftHeight > 0) {
                pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
                leftHeight -= pageHeight;
                position -= 841.89;
                // 避免添加空白页
                if (leftHeight > 0) {
                    pdf.addPage();
                }
            }
        }
        // 可动态生成
        pdf.save(`纳税筹划.pdf`);

    });
};

  

 useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,  这个是解决跨域问题
transformImg给标签加入 crossOrigin = "anonymous"

标签:canvas,const,跨域,contentWidth,ctx,html2canvas,Vue3,pdf
From: https://www.cnblogs.com/alipapa/p/16917455.html

相关文章