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

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

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

javascript 复制代码
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);
    }
}
相关推荐
韩立学长17 小时前
【开题答辩实录分享】以《证劵数据可视化分析项目设计与实现》为例进行答辩实录分享
python·信息可视化·vue
二川bro17 小时前
第30节:大规模地形渲染与LOD技术
前端·threejs
景早17 小时前
商品案例-组件封装(vue)
前端·javascript·vue.js
不说别的就是很菜18 小时前
【前端面试】Vue篇
前端·vue.js·面试
IT_陈寒18 小时前
Java 17实战:我从老旧Spring项目迁移中总结的7个关键避坑点
前端·人工智能·后端
倚肆18 小时前
CSS 动画与变换属性详解
前端·css
blackorbird18 小时前
谷歌 Chrome 浏览器的指纹识别技术,一边反追踪一边搞追踪
前端·chrome
Mintopia19 小时前
🚀 共绩算力:3分钟拥有自己的图像优化服务-CodeFormer:先进的图像算法优化、修复马赛克、提升图片清晰度等
前端·人工智能·ai编程