解决在Vue3中html2canvas图片跨域问题
1 2 | <div v-html= "transformImg(textContent.policyInterpretation)" class = "topicContent" ></div><br><br> const transformImg = (str) =><br> { const replaceCallback = (m, g1) => { return `<img crossOrigin = "anonymous" src=${g1}&t=${Math.random()}>`; }<br> const srcRes = str.replace(/<img [^>]*src=[ '"]([^' "]+)[^>]*>/gi, replaceCallback); return srcRes } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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`); }); }; |
1 | useCORS: true , // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。, 这个是解决跨域问题 |
1 | transformImg给标签加入 crossOrigin = "anonymous" |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律