解决 html2canvas 把svg转成jpg,无法把svg里的image图片正常显示的情况
svg结构
首先需要解决image里的svg里的图片跨域问题,然后需要把image转换成base64格式
如图
代码如图
async downLoadDraw() {// 将SVG容器转换为图片并下载try {this.$message.success('正在生成图片,请稍候...')// 保存当前的变换状态const originalTransform = this.$refs.svgViewerContainer.style.transformconst originalPosition = this.$refs.svgViewerContainer.style.position// 临时重置变换,以便正确捕获this.$refs.svgViewerContainer.style.transform = 'none'this.$refs.svgViewerContainer.style.position = 'relative'// 使用html2canvas将容器转换为canvasconst canvas = await html2canvas(this.$refs.svgViewerContainer, {allowTaint: true,useCORS: true,logging: true,scale: 2, // 提高图片质量backgroundColor: '#ffffff',})// 恢复原始变换this.$refs.svgViewerContainer.style.transform = originalTransformthis.$refs.svgViewerContainer.style.position = originalPosition// 将canvas转换为图片URLconst imageUrl = canvas.toDataURL('image/png')// 创建下载链接const downloadLink = document.createElement('a')downloadLink.href = imageUrldownloadLink.download = '图纸.png'document.body.appendChild(downloadLink)downloadLink.click()document.body.removeChild(downloadLink)this.$message.success('图片已生成并开始下载')} catch (error) {console.error('生成图片时出错:', error)this.$message.error('生成图片失败,请稍后重试')}},