html2canvas 模糊问题处理

在做canvas插入文本框+截图功能的时候使用 html2canvas, 出现保存的图片模糊的问题。
搜了很多帖子,都有略微差别,有的改了源码也不说 = =,
最后找到可用的,清晰度很高的。保存一下。
下面是例子

 let targetDom = document.getElementById('content')
        let targetWidth = targetDom.offsetWidth
        let targetHeight = targetDom.offsetHeight
        let canvas = document.createElement('canvas')
        let scale = window.devicePixelRatio
        canvas.width = targetWidth * scale
        canvas.height = targetHeight * scale
        canvas.style.width = targetWidth * scale + 'px'
        canvas.style.height = targetHeight * scale + 'px'
        canvas.getContext('2d').scale(scale, scale)
        html2canvas(targetDom, {
          allowTaint: false,
          scale,
          canvas,
          logging: false,
          useCORS: true,
          width: targetWidth,
          height: targetHeight,
          ignoreElements: (element) => {
            if (element.id === 'printHide') {
              return true
            }
          }
        }).then(canvas => {
          this.cachePatinUrl = canvas.toDataURL('image/jpeg', 1.0)
          this.cacheHeight = canvas.height
          this.cacheWidth = canvas.width
        })

在这里插入图片描述
很清晰。

### 解决 html2canvas 导出图像 CSS 模糊问题 当使用 `html2canvas` 将 HTML 元素转换为图像时,可能会遇到由于缩放比例不足而导致的模糊问题。为了提高导出图像的质量并减少模糊现象,可以调整渲染选项中的 DPI 设置以及确保所有样式都被正确应用。 #### 提高DPI设置 通过增加每英寸点数(dots per inch, DPI),能够显著提升最终生成图片的清晰度。通常情况下,默认值可能不足以满足高质量需求。因此,在调用 `html2canvas` 方法时应指定较高的 DPI 值[^2]: ```javascript html2canvas(document.querySelector('.report'), { background: '#ffffff', dpi: 300, }).then(function(canvas) { var imgDataUrl = canvas.toDataURL(); }); ``` #### 使用 scale 参数 除了修改 DPI 外,还可以利用 `scale` 属性来放大页面内容后再进行截图操作。这有助于进一步改善细节表现力,特别是在处理复杂布局或细小文字的情况下[^1]: ```javascript html2canvas(document.querySelector('.report'), { backgroundColor: null, useCORS: true, scale: window.devicePixelRatio || 2 // 自适应设备像素比率 }).then(function(canvas) { document.body.appendChild(canvas); }); ``` #### 确保外部资源加载完成 有时,如果某些 CSS 文件或其他依赖项未能及时加载完毕,则可能导致部分样式未被正确应用于目标 DOM 结构中,从而影响到最终输出效果。为此建议等待整个文档完全就绪之后再执行绘图命令: ```javascript window.onload = function() { setTimeout(() => { html2canvas(document.querySelector('.report'),{ allowTaint: false, logging: true, width: document.querySelector('.report').offsetWidth * (window.devicePixelRatio || 2), height: document.querySelector('.report').offsetHeight * (window.devicePixelRatio || 2) }).then((canvas) => { const link = document.createElement('a'); link.href = canvas.toDataURL("image/png"); link.download = "export.png"; link.click(); }); }, 500); // 给予一定时间让所有资源都加载好 }; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值