css - clip-path svg 适用于图像,但不适用于 div
问题描述
在 MDN 上有一个关于如何在图像上使用剪辑路径 svg 的示例。相同的剪辑路径似乎不适用于div
元素。有人可以澄清一下:
- 为什么此代码无法按预期工作
- 一种使 svg 剪辑路径在 div 上工作的方法
剪切图像的示例代码(基于 MDN 文档)
#clipped {
clip-path: url(#cross);
}
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
alt="MDN logo">
<svg height="0" width="0">
<defs>
<clipPath id="cross">
<rect y="110" x="137" width="90" height="90"/>
<rect x="0" y="110" width="90" height="90"/>
<rect x="137" y="0" width="90" height="90"/>
<rect x="0" y="0" width="90" height="90"/>
</clipPath>
</defs>
</svg>
div 上的相同剪辑路径(似乎不起作用)
#clipped {
width: 100px;
height: 100px;
background: black;
clip-path: url(#cross);
}
<div id="clipped"></div>
<svg height="0" width="0">
<defs>
<clipPath id="cross">
<rect y="110" x="137" width="90" height="90"/>
<rect x="0" y="110" width="90" height="90"/>
<rect x="137" y="0" width="90" height="90"/>
<rect x="0" y="0" width="90" height="90"/>
</clipPath>
</defs>
</svg>
解决方案
解决您的问题的方法是使用clipPathUnits="objectBoundingBox"
并构建大小在 0 和 1 之间的剪切路径,如下所示:
#clipped {
margin:1em;
width: 100px;
height: 100px;
background: black;
display:inline-block;
clip-path: url(#cross);
}
#clipped.big{
width: 200px;
height: 200px;
}
<div id="clipped"></div>
<div id="clipped" class="big"></div>
<svg viewBox="0 0 1 1">
<clipPath id="cross" clipPathUnits="objectBoundingBox">
<rect y="0" x="0" width=".4" height=".4"/>
<rect y="0.6" x="0" width=".4" height=".4"/>
<rect y="0" x="0.6" width=".4" height=".4"/>
<rect y="0.6" x="0.6" width=".4" height=".4"/>
</clipPath>
</svg>
推荐阅读
- c# - Xamarin 音频播放器在 Galaxy S8 中不工作
- oracle - 如何使用 tnsnames.ora 将 apache nifi 连接到 oracle db?
- django - django-cors-headers 是否允许从所有来源访问管理站点?
- java - Android NDK:JNI GetMethodID 调用了挂起的异常 java.lang.ClassNotFoundException:找不到类
- windows - 如何使用填充路径的变量在 PowerShell 中导航或执行?
- php - 如何将模型的表名分配或存储到 laravel 中的变量中(这是为了过滤功能)?
- android - 如何为两个 android 主题声明相同的属性?
- java - 使用休眠的子(外键)对象的父(主键)永远不会被设置
- vb.net - 数据输入表单关闭时解锁 SQL Compact (.SDF) 文件
- python - 我无法捕获所有请求错误/异常。某事导致未知错误