You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SVG内嵌视频在Safari中无法正常缩放的问题求助

Safari中SVG foreignObject内视频无法缩放的解决方案

问题背景

通过<foreignObject>标签在SVG中嵌入视频时,Chrome和Firefox能正常显示缩放效果,但在Safari v16.0中,尽管video标签的尺寸已正确缩放(可通过选择工具hover确认),视频内容本身却未跟随容器缩放。且视频必须放在SVG内,无法采用外部放置的方案。已查阅Stack Overflow上关于foreignObject位置问题的解决方案,但未解决缩放问题。

简化后的测试代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body,html{
            width: 100vw;
            height: 100vh;
        }
    </style>
</head>
<body>
    <svg xmlns="http://www.w3.org/2000/svg" width="100%" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 3840 2160">
        <foreignObject width='3840' height='2160'>
            <video width='3840' height='2160' muted playsinline autoplay >
                <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type='video/mp4'>
            </video>
        </foreignObject>
    </svg>
</body>
</html>

测试代码仅包含核心的SVG与视频元素,但Safari中视频内容无法填满容器,和Firefox的正常显示效果差异明显。

可行解决办法

方案1:利用CSS object-fit强制内容填充容器

给video标签添加object-fit: cover并设置宽高为100%,同时用div作为foreignObject的直接子元素,确保尺寸上下文传递正确:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 3840 2160">
    <foreignObject width='3840' height='2160'>
        <div style="width: 100%; height: 100%;">
            <video style="width: 100%; height: 100%; object-fit: cover;" muted playsinline autoplay>
                <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type='video/mp4'>
            </video>
        </div>
    </foreignObject>
</svg>

原理:Safari对foreignObject内媒体元素的尺寸映射存在bug,object-fit会强制视频内容完全填充容器,而div则确保foreignObject的尺寸能正确传递给video。

方案2:采用相对尺寸与SVG比例约束

将foreignObject的宽高设置为100%,让其继承SVG的尺寸,同时给video设置自适应尺寸,配合SVG的preserveAspectRatio维持比例:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 3840 2160" preserveAspectRatio="xMidYMid meet">
    <foreignObject width='100%' height='100%'>
        <video style="max-width: 100%; max-height: 100%; width: auto; height: auto;" muted playsinline autoplay>
            <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type='video/mp4'>
        </video>
    </foreignObject>
</svg>

原理:避免使用绝对尺寸,让foreignObject和video都基于SVG的viewBox自适应,绕过Safari的绝对尺寸计算bug,同时preserveAspectRatio保证视频比例不会变形。

内容的提问来源于stack exchange,提问作者Enrique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:20:43