技能文字描边的三大方法

1次阅读

共计 1532 个字符,预计需要花费 4 分钟才能阅读完成。

该文章参考了张鑫旭的两博文:
paint-order
webkit-text-stroke

webkit-text-stroke 文字描边


描边效果:居中描边
现象:text-stroke-width 会削弱文字的字重,导致文字变细

-webkit-text-stroke: 2px red;
// 等同
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: red;
完美描边效果

可以使用 -webkit-text-stroke 描边文字和非描边文字相互重叠覆盖的方法模拟。技巧就在于 -webkit-text-stroke 描边文字的描边宽度要是要实现的外描边效果宽度的 2 倍。

<div class="texts">
    <p class="text1"> 我是苗冰的小哇啊 </p>
    <p class="text2"> 我是苗冰的小哇啊 </p>
</div>

//css
.texts {position: relative;}
.text1 {
    font-size: 40px;
    position: absolute;
    z-index: 2;
    font-weight: bold;
}
.text2 {
    font-size: 40px;
    font-weight: bold;
    -webkit-text-stroke: green 6px;
    position: absolute;
}


text-stroke属性不行不断累加,如果想要实现多重描边效果,可以借助伪元素多层叠加模拟。

text-shadow

.strok-outside {text-shadow: 0 1px red, 1px 0 red, -1px 0 red, 0 -1px red;}


由于 text-shadow 不支持阴影扩展(box-shadow支持),因此,我们使用四向阴影叠加实现。
如图,当文字特别大的时候,会有齿轮问题。

svg

CSS paint-order作用在 SVG 图形元素上,设置是先绘制描边还是先绘制填充。
在 SVG 中,描边和填充同时都有设置是很常见的,而 SVG 图形的描边和 -webkit-text-stroke 是一样的,都是居中描边。

svg {
    background-color:deepskyblue;
    fill:crimson;
    stroke:white;
    stroke-width:6px;
    font-size:40px;
    font-weight:bold;
}
.paint-order {paint-order:stroke;}
<svg xmlns="http://www.w3.org/2000/svg">
    <text x="10" y="50"> 我是测试小霸王 </text>
    <text x="10" y="120" class="paint-order"> 我是测试小霸王 </text>
</svg>

//`||` 表示或者,可以并存
paint-order: normal | [fill || stroke || markers]
paint-order: markers stroke;
  • normal: 默认值。绘制顺序是 fill stroke markers。图形绘制是后来居上的,因此默认是描边覆盖填充,标记覆盖描边。
  • fill: 先填充。
  • stroke: 先描边,然后再填充或者标记。
  • markers: 先标记。下图坐标值的两个箭头,以及折线上的红色小圆点就是标记,<marker>元素绘制的

CSS paint-order 可以作用在 SVG 的以下这些元素上:<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textPath>,~~~~ 以及<tspan>

paint-order也可以直接作为 XML 属性用在上面这些元素上。
兼容性也是不错的

正文完
 0