【问题标题】:How can I change the font of when typing along a SVG path?沿 SVG 路径输入时如何更改字体?
【发布时间】:2021-09-30 02:05:29
【问题描述】:

我有以下代码沿路径添加字母以模拟打字效果。但是,我希望根据底部的图像,最后一点文本“这是我们的果酱”与第一个不同的字体。有没有办法做到这一点?我一直在尝试动态添加一个类,但它会更新整个 tspan,我无法确定是否可以添加第二个 tspan 或类似的?

var input = "";
var draw = SVG().addTo("#drawing").viewbox(0, 0, 300, 140);
var text = draw.text(function (add) {
  add.tspan(input).attr("class", "title");
});

const stringToType =
  "Great design is not just our bread + butter ... it's our jam";

textPath = text.path(
  "M 10 20 C 23 15 45 12 64 20 C 99 36 96 48 135 57 C 172 65 188 61 204 58 L 204 58"
);

var count = 0;

var paused = 0;
var secondPause = 0;
var complete = false;
var restart = false;

var newInput = "";

var timer = setInterval(function () {
  if (!paused) {
    var textToAdd = stringToType[count];

    newInput = newInput + textToAdd;
    textPath.tspan(newInput).attr("class", "title");

    count++;
    if (count === stringToType.length) {
      paused++;
    }
  } else {
    clearInterval(timer);
  }
}, 100);
body {
  font-size: 8px;
}
<div id="drawing"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/3.1.1/svg.min.js"></script>

我想要达到的效果(忽略俗气的一点):

【问题讨论】:

  • 你可以在一个 SVG 文本元素中拥有多个 tspan——当你到达字符串的那个部分时,只需添加第二个具有粗体字体的类

标签: javascript css svg svg.js


【解决方案1】:

您可以使用tspan 标签来设置文本的一部分:

let text1 = `Great design is not just our bread + butter... `;
let text2 = `it's our jam`;
let pointer1 = 1;
let pointer2 = 1;

let text_path = document.querySelector('textPath');

let write = setInterval(() => {
    let text = text1.slice(0,pointer1);
    if(pointer1 >= text1.length){
        text += '<tspan>';
        text += text2.slice(0,pointer2);
        text += '</tspan>'
        pointer2++;
    } else {
        pointer1++;
    }
    
    text_path.innerHTML = text;
    
    if(pointer2> text2.length){
        clearInterval(write);
    }
}, 100)  
<svg viewBox="0 0 300 140" xmlns="http://www.w3.org/2000/svg" fill="orange">
    <style>
        tspan {
            font-weight: bold;
        }
    </style>
    
    <path id="textPath" fill="none" d="M 10 20 C 23 15 45 12 64 20 C 99 36 96 48 135 57 C 172 65 188 61 204 58 L 204 58" />
    
    <text>
        <textPath href="#textPath" font-size="9.2"></textPath>
    </text>
</svg>

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 2016-07-18
    • 2014-02-05
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    相关资源
    最近更新 更多