如何在React的styled-components中将SVG用作遮罩实现渐变仅在SVG区域显示
实现方案
你需要的效果可以通过CSS mask 属性实现,核心逻辑是将渐变层用你的blob SVG作为遮罩裁剪,仅保留和blob形状重叠的区域可见,其余部分透明,依托父容器白色背景即可实现SVG外全白的效果。
具体修改步骤
- 给渐变层
.backdropColor添加和blob完全同步的动画,同时配置mask属性用你的blob形状裁剪渐变 - 移除原来的
CardBlob1组件引用,裁剪后的渐变层已经自带动态blob效果
修改后的核心代码
import React from "react"; import styled, { keyframes } from "styled-components"; import { FaRegClipboard } from "react-icons/fa"; const Features = () => { return ( <Card> <BlobContainer> <div className="backdropColor"></div> <FaRegClipboard className="card-icon" /> </BlobContainer> </Card> ); }; export default Features; const transformBlob = keyframes` 0% { transform: scale(1) rotate(0); } 25% { transform: scale(0.9) rotate(55deg); } 50% { transform: scale(0.8) rotate(180deg); } 75% { transform: scale(0.9) rotate(55deg); } 100% { transform: scale(1) rotate(0); } `; const Card = styled.div` align-items: center; background: #ffffff; border: 1px solid black; border-radius: 5px; display: grid; justify-content: center; padding: 50px 43px; transition: all 0.5s linear; width: 260px; `; const BlobContainer = styled.div` align-items: center; display: flex; justify-content: center; position: relative; .backdropColor { height: 100px; background-image: linear-gradient( to top, #fcc5e4 0%, #fda34b 15%, #ff7882 35%, #c8699e 52%, #7046aa 71%, #0c1db8 87%, #020f75 100% ); position: absolute; width: 100px; /* 新增遮罩和同步动画配置 */ animation: ${transformBlob} 20s linear infinite; -webkit-mask: url("data:image/svg+xml,%3Csvg id='visual' transform='translate(128.81 125.55)' width='348.26' height='278.9' version='1.1' viewBox='0 0 348.26 278.9' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m342.31 70.846c23.3 57.1-25.1 152.2-88.3 189.1-63.1 36.8-140.9 15.5-191.3-25.4-50.4-40.9-73.5-101.4-57.9-147.8 15.6-46.4 69.8-78.8 144.4-85.5 74.7-6.6 169.8 12.5 193.1 69.6' fill='%23fff'/%3E%3C/svg%3E"); mask: url("data:image/svg+xml,%3Csvg id='visual' transform='translate(128.81 125.55)' width='348.26' height='278.9' version='1.1' viewBox='0 0 348.26 278.9' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m342.31 70.846c23.3 57.1-25.1 152.2-88.3 189.1-63.1 36.8-140.9 15.5-191.3-25.4-50.4-40.9-73.5-101.4-57.9-147.8 15.6-46.4 69.8-78.8 144.4-85.5 74.7-6.6 169.8 12.5 193.1 69.6' fill='%23fff'/%3E%3C/svg%3E"); -webkit-mask-size: 100% 100%; mask-size: 100% 100%; } .card-icon { color: #ffffff; height: 25px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 25px; z-index: 10; } `;
兼容说明
mask 属性已覆盖所有主流现代浏览器,添加-webkit-前缀可兼容旧版webkit内核浏览器,无需额外降级处理。
内容的提问来源于stack exchange,提问作者Doggednewbie
相关产品推荐
相关产品推荐

