SVG图案旋转不变性需求:寻求全局统一旋转的实现方案
解决SVG图案随对象旋转的问题
要让所有填充哈希图案的对象,不管自身怎么旋转,图案的红线方向都保持一致,你可以通过给图案添加反向旋转来抵消对象旋转的影响,结合patternUnits="userSpaceOnUse"的全局坐标特性就能实现。
可行代码示例
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"> <defs> <pattern id="hashPattern" patternUnits="userSpaceOnUse" width="10" height="10"> <path d="M 0 0 L 10 10" stroke="red" stroke-width="2" /> </pattern> <!-- 把形状和填充分离,方便单独控制每个实例的图案变换 --> <g id="yourShape"> <ellipse cx="25" cy="25" rx="15" ry="25" stroke="black" /> </g> </defs> <!-- 无旋转的对象,直接用基础图案填充 --> <use href="#yourShape" x="20" y="20" fill="url(#hashPattern)" /> <!-- 对象转45°,图案就转-45°抵消 --> <use href="#yourShape" x="100" y="20" transform="rotate(45 125 45)" fill="url(#hashPattern) patternTransform='rotate(-45)'" /> <!-- 对象转90°,图案就转-90°抵消 --> <use href="#yourShape" x="20" y="100" transform="rotate(90 45 125)" fill="url(#hashPattern) patternTransform='rotate(-90)'" /> <!-- 对象转180°,图案就转-180°抵消 --> <use href="#yourShape" x="100" y="100" transform="rotate(180 125 125)" fill="url(#hashPattern) patternTransform='rotate(-180)'" /> </svg>
原理说明
patternUnits="userSpaceOnUse"让图案的坐标基于SVG全局画布,而非对象自身的局部坐标,但对象旋转时,图案会被对象的旋转“带歪”。- 给图案添加
patternTransform并设置与对象旋转角度相反的值,刚好能抵消对象旋转的影响,让红线方向始终和全局画布保持一致。
另一种简化方案(无需逐个设置反向旋转)
如果所有对象的图案都要固定方向,也可以预先把图案的线条方向固定好,调整图案的尺寸和视口避免间隙:
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"> <defs> <!-- 预先把线条设成全局固定方向,调整viewBox和尺寸适配旋转后的边界 --> <pattern id="fixedHash" patternUnits="userSpaceOnUse" width="14.14" height="14.14" viewBox="-5 -5 14.14 14.14"> <path d="M -5 5 L 5 -5" stroke="red" stroke-width="2" /> </pattern> <g id="yourShape"> <ellipse cx="25" cy="25" rx="15" ry="25" stroke="black" fill="url(#fixedHash)" /> </g> </defs> <use href="#yourShape" x="20" y="20" /> <use href="#yourShape" x="100" y="20" transform="rotate(45 125 45)" /> <use href="#yourShape" x="20" y="100" transform="rotate(90 45 125)" /> <use href="#yourShape" x="100" y="100" transform="rotate(180 125 125)" /> </svg>
内容的提问来源于stack exchange,提问作者Philipp Kolbe
相关产品推荐
相关产品推荐

