如何为旋转的SVG圆形文本填充图案图像?
解决SVG圆形旋转文本填充图案的问题
嘿,我来帮你搞定这个SVG文本填充图案不生效的问题!你的代码已经搭好了基础框架,只需要调整两个关键地方就能让图案正确显示在旋转的文本上:
问题分析
你的代码里有两个核心问题导致图案填充失效:
<pattern>标签缺少尺寸和坐标系属性,浏览器无法正确解析图案的平铺规则<textPath>的fill被设为white,直接覆盖了图案填充的设置
修正后的代码
HTML部分
<div id="container"> <div id="circle"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="300px" height="300px" viewBox="0 0 300 300" enable-background="new 0 0 300 300" xml:space="preserve"> <defs> <!-- 补充pattern必要属性,指定尺寸和坐标系 --> <pattern id='my_portrait' width="100" height="100" patternUnits="userSpaceOnUse"> <image xlink:href="http://gastv.mx/wp-content/uploads/2014/05/jumex.jpg" x="-30" y="-30" width="380" height="267" /> </pattern> <path id="circlePath" d=" M 150, 150 m -60, 0 a 60,60 0 0,1 120,0 a 60,60 0 0,1 -120,0 " /> </defs> <!-- 如果需要填充内部空心圆,把fill改成url(#my_portrait) --> <circle cx="150" cy="100" r="75" fill="none"/> <g id="rotating_text"> <use xlink:href="#circlePath" fill="rgb(81,84,77)" stroke="black" stroke-width="2px"/> <text> <!-- 将fill改为图案引用,替换原来的white --> <textPath xlink:href="#circlePath" fill="url(#my_portrait)">Curse this circular mass of misery!!!</textPath> </text> </g> </svg> </div> </div>
CSS部分(无需修改,保持原动画逻辑即可)
#circle svg { width: 100%; -webkit-animation-name: rotate; -moz-animation-name: rotate; -ms-animation-name: rotate; -o-animation-name: rotate; animation-name: rotate; -webkit-animation-duration: 20s; -moz-animation-duration: 20s; -ms-animation-duration: 20s; -o-animation-duration: 20s; animation-duration: 20s; -webkit-animation-iteration-count: infinite; -moz-animation-iteration-count: infinite; -ms-animation-iteration-count: infinite; -o-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-timing-function: linear; -moz-animation-timing-function: linear; -ms-animation-timing-function: linear; -o-animation-timing-function: linear; animation-timing-function: linear; } @-webkit-keyframes rotate { from { -webkit-transform: rotate(360deg); } to { -webkit-transform: rotate(0); } } @-moz-keyframes rotate { from { -moz-transform: rotate(360deg); } to { -moz-transform: rotate(0); } } @-ms-keyframes rotate { from { -ms-transform: rotate(360deg); } to { -ms-transform: rotate(0); } } @-o-keyframes rotate { from { -o-transform: rotate(360deg); } to { -o-transform: rotate(0); } } @keyframes rotate { from { transform: rotate(360deg); } to { transform: rotate(0); } }
关键修改说明
完善
<pattern>属性:width和height:定义图案单元的尺寸,这里设为100x100像素,你可以根据需求调整patternUnits="userSpaceOnUse":指定图案使用SVG的用户坐标系,确保图案按你设置的尺寸正确平铺
修正文本填充设置:
- 把
<textPath>的fill="white"改成fill="url(#my_portrait)",这样文本就会使用你定义的图案填充了
- 把
如果还想给中间的空心圆也填充图案,只需要把<circle>标签的fill="none"改成fill="url(#my_portrait)"就行啦~
内容的提问来源于stack exchange,提问作者Trenton_Hjorth
相关产品推荐
相关产品推荐

