解决html-to-image在 ios 上dom里面的图片不显示出来

发布于:2025-08-17 ⋅ 阅读:(17) ⋅ 点赞:(0)

原因:在iOS的Safari浏览器,使用页面生成图片,如dom里面有图片,则会先进行加载资源,但是这个加载速度会随着图片大小而延长,但是页面生成图片的时机总会比这个快。所以会导致dom里面的图片不会出来

解决方案:这里我是用了vue3。

const captureSnapshot = async (targetElement,options,previousDataUrl = "") => {
  const dataUrl = await htmlToImage.toPng(targetElement,options)

  // 这是判断因为 dataUrl 对快照图像进行了编码,而 Safari 现在渲染的内容比上次更多。dataUrl 的长度提供了一些关于渲染内容的信息。直到dataUrl.length停止增加,表明 Safari 已完成渲染。
  return (dataUrl.length !== previousDataUrl.length)
    ? captureSnapshot(targetElement,options,dataUrl)
    : dataUrl
}

// 页面上传图片
const generateReport = () => {
    let offscreenContainer = document.getElementById('my-node');

    // 这个options无所谓,主要是captureSnapshot方法和下面给img加上decoding="sync"属性
    let options = {
        quality: 0.95,
        backgroundColor: '#ffffff',
        width: offscreenContainer.scrollWidth,
        height: offscreenContainer.scrollHeight,
        pixelRatio: window.devicePixelRatio > 2 ? 2 : window.devicePixelRatio,
        filter: function (node) {
            if (node.tagName === 'IMG' && (!node.src || node.src === '')) {
                return false;
            }
            if (node.classList && node.classList.contains('landscape-wrap')) {
                return false;
            }
            if (node.classList && node.classList.contains('link-more')) {
                return false;
            }
            return true;
        },
        canvasTimeout: 15000,
        useCORS: true,
        skipAutoScale: true,
        allowTaint: true,
        // iOS兼容性设置
        preferredFontFormat: 'woff2',
        skipFonts: false,
        style: {
            transform: 'scale(1)',
            transformOrigin: 'top left'
        },
    };

    try {
        // 确保所有图表都已渲染完成
        await nextTick();

        // 这个也是关键代码。给offscreenContainer里面的img添加decoding="sync"属性,不然ios上还是会显示不出dom里面的图片
        offscreenContainer.querySelectorAll('img').forEach(img => {
            img.setAttribute('decoding', 'sync');
        });
        
        // 转换为png格式
        imgSrc.value = await captureSnapshot(offscreenContainer,options);

    } catch (error) {
        console.error('生成失败:', error);
    }
}


 


网站公告

今日签到

点亮在社区的每一天
去签到