解决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);
    }
}
相关推荐
向下的大树15 小时前
npm 最新镜像,命令导致下载错误
前端·npm·node.js
宁雨桥15 小时前
Service Worker:前端离线化与性能优化的核心技术
前端·性能优化
IT_陈寒15 小时前
SpringBoot实战:这5个隐藏技巧让我开发效率提升200%,90%的人都不知道!
前端·人工智能·后端
ObjectX前端实验室15 小时前
【图形编辑器架构】节点树与渲染树的双向绑定原理
前端·计算机图形学·图形学
excel15 小时前
Vue2 与 Vue3 生命周期详解与对比
前端
一只猪皮怪516 小时前
React 18 前端最佳实践技术栈清单(2025版)
前端·react.js·前端框架
Misnice16 小时前
React渲染超大的字符串
前端·javascript·react.js
天天向上的鹿茸16 小时前
用矩阵实现元素绕不定点旋转
前端·线性代数·矩阵
李鸿耀19 小时前
主题换肤指南:设计到开发的完整实践
前端
2501_9160137420 小时前
iOS 26 系统流畅度检测 从视觉特效到帧率稳定的实战策略
android·macos·ios·小程序·uni-app·cocoa·iphone