【SVG篇二】textpath路径文字形状及动画

9094次浏览

前言

上节课我们讲了基本形状转为path,转换为path之后,就可以用textpath 做沿路径布局的文字了。如下布局

haorooms svg path 测试

代码如下:

 <svg viewBox="0 60 200 100" height="120">
  <defs>
  <path id="haoroomsPath" fill="none" stroke="red" d="M0,80 q10,30 90,20 q100,-30 120,80" />
  </defs>
  <text>
    <textPath href="#haoroomsPath">
        haorooms svg path 测试
    </textPath>
  </text>
</svg>

解释:

viewBox 四个参数是最小X轴数值,最小y轴数组,宽度,高度

在defs元素中定义的图形元素不会直接呈现。

textPath要指定href 是那个path下面的,即要指定id

圆形,心形等其他效果一样的。但是必须是path路径,基本形状例如上节课的circle是不可以的。

圆形布局如下:

这里是haorooms圆形测试,哈哈哈哈哈,测试结束
<svg viewBox="0 0 300 150" height="150">
  <defs>
  <path id="haoroomsCircle"  fill="none" d="M90 75a60 60 0 1 0 120 0a60 60 0 1 0 -120 0z"/>
  </defs>
  <text>
    <textPath href="#haoroomsCircle">这里是haorooms圆形测试,哈哈哈哈哈,测试结束</textPath>
  </text>
</svg>
⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
<svg viewBox="-10 -10 180 168" width="160" height="148">
  <defs><path id="haoroomsPathx" d="M118,0c-17,0-31.5,13.5-38,28C73.5,13.5,59,0,42,0C19,0,0,19,0,42c0,47,47.5,59.5,80,106
    c30.5-46.5,80-60.5,80-106C160,19,141,0,118,0z"/></defs>
  <text>
    <textPath href="#haoroomsPathx">⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐</textPath>
  </text>
</svg>

动画

offset-path让元素沿着不规则路径运动

如下代码就可以让小鸟飞起来

<style>
.brid-fly {
    motion-path: path("M10,80 q100,120 120,20 q140,-50 160,0");
    offset-path: path("M10,80 q100,120 120,20 q140,-50 160,0");
    animation: move 3s linear infinite;
}
@keyframes move {
  /* 之前语法 */
  100% { motion-offset: 100%;}
  /* 当前规范语法 */
  100% { offset-distance: 100%;}
}
</style>

<img src="https://www.haorooms.com/uploads/images/bower.png" width="40" height="43" class="brid-fly">
<svg width="280" height="150" viewBox="0 0 280 150">
  <defs>
    <path d="M10,80 q100,120 120,20 q140,-50 160,0" stroke="#cd0000" stroke-width="2" fill="none" />
  </defs>
</svg>

其中用到了两个CSS属性,一个是offset-path,表示运动的路径,另外一个则是offset-distance,我是运动的距离,可以是数值或者百分比单位,如果是100%则表示正好把所有的路都跑完了。

除了offset-path和offset-distance这两个CSS属性,还有其他一些相关的属性,例如offset-rotation(规范上显示的是offset-rotate,浏览器是无效不识别的),表示运动的角度,默认是auto,表示自动计算当前路径的切线方向,并朝着这个方向前进.

例如:

offset-rotation: 30deg

延伸

除了沿路径布局之外,我们有时候还有要验证障碍物布局的方式。这种布局可以用CSS shapes

关键词如下:

/* 关键字值 */
shape-outside: none;
shape-outside: margin-box;
shape-outside: content-box;
shape-outside: border-box;
shape-outside: padding-box;

/* 函数值 */
shape-outside: circle();
shape-outside: ellipse();
shape-outside: inset(10px 10px 10px 10px);
shape-outside: polygon(10px 10px, 20px 20px, 30px 30px);

/* <url>值 */
shape-outside: url(image.png);

/* 渐变值 */
shape-outside: linear-gradient(45deg, rgba(255, 255, 255, 0) 150px, red 150px);

看我之前的文章iphoneX适配问题想到的:https://www.haorooms.com/post/iphonex_shipei

Tags: svgtextpath

相关文章: