如何在SVG中对旋转后的元素执行裁剪操作?
解决SVG先旋转元素再裁剪的问题
SVG中clip-path默认在元素的本地坐标系下生效——直接给带transform的元素加clip-path,会先完成裁剪,再执行元素的旋转/变换,和你需要的顺序刚好相反。
要实现先旋转元素,再用固定的未旋转矩形裁剪,最直观的方法是用<g>容器拆分裁剪和变换的作用对象:
- 给
<g>应用clip-path(容器无变换,裁剪区域保持全局坐标系的未旋转状态) - 把旋转操作单独作用于
<g>内部的矩形元素
修正后的代码示例1:
<svg width="800" height="800"> <defs> <clipPath id="Clip01"> <rect x="50" y="50" width="100" height="100" /> </clipPath> </defs> <g clip-path="url(#Clip01)"> <rect x="50" y="50" width="100" height="100" fill="red" transform="rotate(20, 100, 100)" /> </g> </svg>
修正后的代码示例2(缩小裁剪矩形):
<svg width="800" height="800"> <defs> <clipPath id="Clip01"> <rect x="50" y="50" width="100" height="50" /> </clipPath> </defs> <g clip-path="url(#Clip01)"> <rect x="50" y="50" width="100" height="100" fill="red" transform="rotate(20, 100, 100)" /> </g> </svg>
另一种可选方法(无需<g>容器):
如果不想用容器,也可以给clipPath内的矩形应用反向变换,抵消元素的旋转,让裁剪区域对齐全局坐标系:
<svg width="800" height="800"> <defs> <clipPath id="Clip01"> <rect x="50" y="50" width="100" height="50" transform="rotate(-20, 100, 100)" /> </clipPath> </defs> <rect clip-path="url(#Clip01)" x="50" y="50" width="100" height="100" fill="red" transform="rotate(20, 100, 100)" /> </svg>
内容的提问来源于stack exchange,提问作者stevenvh
相关产品推荐
相关产品推荐

