2

Есть такой пример, чтобы долго не объяснять, меняйте последнюю координату и увидите что происходит.

Js, к данной проблеме не имеет ни какого отношения (смотреть пример 2), функция которая меняет последнюю координату path, только для того, чтобы людям которые будут читать вопрос, было бы легко и быстро увидеть проблему.

Что касается замены path на rect, не получиться... Это малая часть большого сложного, где нельзя заменить path на rect.

const input = document.querySelector('input');
document.querySelector('.path').setAttribute('d', 'M5 250 495 ' + input.value);
input.addEventListener('input', function() {
  document.querySelector('.path').setAttribute('d', 'M5 250 495 ' + input.value);
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100vw;
  height: 100vh;
  background-color: #272727;
}

div.wrapper {
  height: 500px;
  background-color: #10e7dd;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

input {
  height: 50px;
  width: 100px;
  text-align: center;
  font-size: 25px;
}

svg {
  background-color: grey;
}
<div class="wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
        <defs>
          <linearGradient id="gradient" x1="0%" x2="100%" y1="0%"  y2="0%">
            <stop offset="0%" stop-color="#f00" />
            <stop offset="100%" stop-color="#00f" />
          </linearGradient>
        </defs>
      <path class="path"  stroke-width="100" stroke="url(#gradient)" fill="none" d="M5 250 495 250.1"/>
      
      </svg>
  <div>
    <input type="number" value="250">
  </div>
</div>

Вот как выглядит без JS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100vw;
  height: 100vh;
  background-color: #272727;
}

div.wrapper {
  height: 500px;
  background-color: #10e7dd;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

svg {
  background-color: grey;
}
<div class="wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
            <defs>
              <linearGradient id="gradient" x1="0%" x2="100%" y1="0%"  y2="0%">
                <stop offset="0%" stop-color="#f00" />
                <stop offset="100%" stop-color="#00f" />
              </linearGradient>
            </defs>
          <path class="path"  stroke-width="100" stroke="url(#gradient)" fill="none" d="M5 250 495 250"/>
          
          </svg>
</div>

Что это, баг? Как это исправить?

6
  • В части SVG всё работает нормально. Причину нужно искать в JS, что-то не так с присвоением значения для Path 31 янв 2020 в 14:44
  • Js я для наглядности написал... Без js тоже самое
    – Air
    31 янв 2020 в 15:13
  • а как должно выглядеть ...без js ? 31 янв 2020 в 15:22
  • @Air Удалил JS вот так выглядит и в FF и Chrome i.stack.imgur.com/h7I1O.png 31 янв 2020 в 15:34
  • @zhurof, благодарю, то что надо. напиши ответом... я его приму
    – Air
    31 янв 2020 в 22:04

2 ответа 2

3

Есть предположение, что высота элемента из горизонтальной линии равна нулю (обводка не влияет на размер элемента), а размеры градиента по умолчанию считается от размеров элемента (objectBoundingBox). Если добавить для градиента gradientUnits="userSpaceOnUse", то работает.
Однако при этом стоит учитывать, что координаты градиента будут рассчитываться относительно системы координат всего SVG-элемента.

const input = document.querySelector('input');
document.querySelector('.path').setAttribute('d', 'M5,250 495,' + input.value);
input.addEventListener('input', function() {
  document.querySelector('.path').setAttribute('d', 'M5,250 495,' + input.value);
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100vw;
  height: 100vh;
  background-color: #272727;
}

div.wrapper {
  height: 500px;
  background-color: #10e7dd;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

input {
  height: 50px;
  width: 100px;
  text-align: center;
  font-size: 25px;
}

svg {
  background-color: grey;
}
<div class="wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
            <defs>
              <linearGradient id="gradient" x1="0%" x2="100%" y1="0%"  y2="0%" gradientUnits="userSpaceOnUse">
                <stop offset="0%" stop-color="#f00" />
                <stop offset="100%" stop-color="#00f" />
              </linearGradient>
            </defs>
          <path class="path"  stroke-width="100" stroke="url(#gradient)" fill="none" d="M5,250 495,250"/>
          
          </svg>
  <div>
    <input type="number" value="250">
  </div>
</div>

4
  • codepen.io/topicstarter/pen/abzgrVX работает же без gradientUnits="userSpaceOnUse" но если стереть "M5 250 495 250.1" единичку то не работает .. 1 фев 2020 в 5:48
  • 1
    @MaximLensky Потому что в таком случае высота .path не равняется нулю и у градиента есть размеры для отрисовки при objectBoundingBox (значение по умолчанию). Думаю дело в этом.
    – zhurof
    1 фев 2020 в 6:09
  • С вертикальной линией кстати таже фигня
    – zhurof
    1 фев 2020 в 6:11
  • да точно ...проверил 1 фев 2020 в 6:26
2

Заменил линию на прямоугольник. Может так надежней будет, в смысле применения градиентов, для вашего приложения.

Изменение размеров градиентной полосы в зависимости от input

var slider = document.getElementById("slider");
var rect = document.getElementById("path");

slider.addEventListener("change", function(evt) {

  var sliderValue = evt.target.value;
   rect.setAttribute("width", sliderValue);
   
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 50vw;
  height: 100vh;
  background-color: #272727;
}

div.wrapper {
  height: 500px;
  background-color: #10e7dd;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

input {
  height: 50px;
  width: 100px;
  text-align: center;
  font-size: 25px;
}

svg {
  background-color: grey;
}
<div class="wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
        <defs>
          <linearGradient id="gradient" x1="0%" x2="100%" y1="0%"  y2="0%">
            <stop offset="0%" stop-color="#f00" />
            <stop offset="100%" stop-color="#00f" />
          </linearGradient>
        </defs>
      <!-- <path class="path"  stroke-width="100" stroke="url(#gradient)" fill="none" d="M5 250 495 250.1"/> -->
      <rect id="path" x="5" y="250" width="10" height="100" fill="url(#gradient)" >
	   
	   </rect>
      </svg>
  <div>
    <input id="slider" type="range" min="10" step="1" max="490"  value="0">
  </div>
</div>

Анимация градиентной полосы

var slider = document.getElementById("slider");
var anim = document.getElementById("anim");

slider.addEventListener("change", function(evt) {

  var sliderValue = evt.target.value;
  var currentTo = anim.getAttribute("to");
  anim.setAttribute("from", 10);
  anim.setAttribute("to", sliderValue);
  anim.beginElement();

});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 50vw;
  height: 100vh;
  background-color: #272727;
}

div.wrapper {
  height: 500px;
  background-color: #10e7dd;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

input {
  height: 50px;
  width: 100px;
  text-align: center;
  font-size: 25px;
}

svg {
  background-color: grey;
}
<div class="wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
        <defs>
          <linearGradient id="gradient" x1="0%" x2="100%" y1="0%"  y2="0%">
            <stop offset="0%" stop-color="#f00" />
            <stop offset="100%" stop-color="#00f" />
          </linearGradient>
        </defs>
      <!-- <path class="path"  stroke-width="100" stroke="url(#gradient)" fill="none" d="M5 250 495 250.1"/> -->
      <rect class="path" x="5" y="250" width="10" height="100" fill="url(#gradient)" >
	   <animate id="anim"
	     attributeName="width"
		   dur="1s"
       fill="freeze"/>
	   </rect>
      </svg>
  <div>
    <input id="slider" type="range" min="0" step="1" max="490"  value="0">
  </div>
</div>

1
  • 1
    Alexandr_TT, благодарю, но это немного не то... Но имеет право на жизнь
    – Air
    31 янв 2020 в 22:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.