沿着曲线移动文字

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。 立即开始使用 200 美元的免费额度!

前几天,《纽约时报》上有一篇有趣的文章,描述了伊丽莎白·沃伦和她的工作人员让公众 与沃伦自拍 的花哨方式。 但是……这些照片实际上并不是自拍,因为它们是由其他人拍摄的。 这篇文章有一行滑稽的文字,在您向下滚动页面时,它会在一条弯曲的线上摆动。

让我们看看他们是如何做到的。

动画

弯曲的线条作为 <path>SVG 中绘制,并且 <text> 通过 <textPath> 设置在其上。

<svg width="100%" height="160px" viewBox="0 0 1098.72 89.55">
    <path id="curve" fill="transparent" d="M0.17,0.23c0,0,105.85,77.7,276.46,73.2s243.8-61.37,408.77-54.05c172.09,7.64,213.4,92.34,413.28,64.19"></path>
    <text width="100%" style="transform:translate3d(0,0,0);">
        <textPath style="transform:translate3d(0,0,0);" alignment-baseline="top" xlink:href="#curve">*The pictures are not technically selfies.</textPath>
    </text>
</svg>

移动技巧是通过调整 textPath 元素的 startOffset 属性来实现的。

我不确定他们是如何做到的,但是我们可以通过观察页面的滚动位置并以某种方式设置该属性来进行一些快速的临时计算,使其以我们想要的速度和距离移动。

const textPath = document.querySelector("#text-path");

const h = document.documentElement, 
      b = document.body,
      st = 'scrollTop',
      sh = 'scrollHeight';

document.addEventListener("scroll", e => {
  let percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
  textPath.setAttribute("startOffset", (-percent * 40) + 1200)
});

这是一个演示

查看 Chris Coyier 的 CodePen
自拍爬行
(@chriscoyier)
CodePen 上。

出于各种原因,曲线上的文字是一种很酷的设计外观!它在网络上并不常见,因此当它被使用时,它就会脱颖而出。

查看 wheatup 的 CodePen
CodePen 挑战:炉石传说卡牌
(@wheatup)
CodePen 上。