Как рисовать слова на прокрутке с помощью svg?

Я хочу, чтобы всякий раз, когда пользователь прокручивает мою веб-страницу, отображалась надпись «Живи в блаженстве». Мне удалось нарисовать букву L, но я не знаю, как мне работать с другими элементами. Я пытался использовать несколько svgs, но это не дало желаемого результата. Ниже приведен мой код: -

// Get the id of the <path> element and the length of <path>
    var triangle = document.getElementById("triangle");
    var length = triangle.getTotalLength();
    
    // The start position of the drawing
    triangle.style.strokeDasharray = length;
    
    // Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
    triangle.style.strokeDashoffset = length;
    
    // Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
    window.addEventListener("scroll", myFunction);
    
    function myFunction() {
    var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
    
      var draw = length * scrollpercent;
      
      // Reverse the drawing (when scrolling upwards)
      triangle.style.strokeDashoffset = length - draw;
    }
#mySVG {
      position: fixed;
      top: 20%;
      width: 400px;
      height: 210px;
      margin-left: 20%;
    }
    
    body {
  height: 2000px;
  background: #f1f1f1;
}
<html>
<body>
<head>
<meta name = "viewport" content = "width=device-width, initial-scale=1">
</head>
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>


    <svg id = "mySVG">
      <path fill = "none" stroke = "red" stroke-width = "3" id = "triangle" d = "M75 20 L75 200 L160 200 0 Z" />
      Sorry, your browser does not support inline SVG.
    </svg>
    
</body>
</html>

Спасибо

Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
0
0
123
1

Ответы 1

Это из MDN:

Свойство Element.scrollTop получает или задает количество пикселей, на которое содержимое элемента прокручивается по вертикали.

Свойство Element.scrollHeight только для чтения — это измерение высоты содержимого элемента, включая содержимое, невидимое на экране из-за переполнения.

Свойство Element.clientHeight только для чтения равно нулю для элементов без CSS или встроенных блоков макета; в противном случае это внутренняя высота элемента в пикселях. Он включает отступы, но не включает границы, поля и горизонтальные полосы прокрутки (если они есть).

Я использую все эти свойства для вычисления dashoffset пути, чтобы анимация заканчивалась, когда заканчивается прокрутка.

Надеюсь, это то, что вам нужно.

// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();
var dasharray = length;
var dashoffset = length;

// The start position of the drawing
triangle.style.strokeDasharray = dasharray;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = dashoffset;



scrollingContent.addEventListener(
  "scroll",
  function(e) {

    dashoffset =
      length -
      e.target.scrollTop /
      ((e.target.scrollHeight - scrollingContent.clientHeight) / length);
    triangle.style.strokeDashoffset = dashoffset;
  },
  false
);
#mySVG {
  position: fixed;
  top: 5%;
  width: 400px;
  height: 210px;
  margin-left: 10%;
  border:1px solid;
  background:rgba(255,255,255,.85);
  
  pointer-events:none;
}

#scrollingContent{display:block;width:20em; max-height:100vh; overflow:scroll}
<svg id = "mySVG">
  <path fill = "none" stroke = "red" stroke-width = "3" id = "triangle" d = "M75 20 L75 200 L160 200" />
  Sorry, your browser does not support inline SVG.
</svg>
<p id = "scrollingContent">
I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:-0
I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:-0
I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:-0
I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:I want that whenever a user scrolls my web page, "Live in Bliss" should be drawn. I have managed to draw L, but am not sure how can I go with other elements. I tried using multiple svgs, but it wasn't giving the desired output. Following is my code:-
</p>

Спасибо, но мой желаемый результат - это что-то другое. Я отредактировал свой вопрос, чтобы было понятно. Пожалуйста, запустите фрагмент кода. После прокрутки вы увидите, что L нарисован. Я просто хочу нарисовать другие элементы, чтобы завершить слово «Жить в блаженстве». Спасибо

Shashankk Shekar Chaturvedi 02.04.2019 11:27

Другие вопросы по теме