Объединить clipPath, pattern и linearGradient в SVG

224
02 апреля 2018, 22:03

Я пытаюсь создать фон, состоящий из градиента нескольких точек, от зеленого до желтого, слева направо. Поэтому идея заключалась в том, чтобы создать путь, заполнить его градиентом и clipPath с pattern:

<svg width='100' height='100' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="green"></stop> 
      <stop offset="100%" stop-color="yellow"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width=".1" height=".1"> 
      <circle cx="2" cy="2" r="2" fill="green"></circle> 
    </pattern> 
    <clipPath id="img-dotted-clip"> 
      <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-dots)"></path> 
    </clipPath> 
  </defs> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" clip-path="url(#img-dotted-clip)"></path> 
</svg>

Градиент работает нормально, clip-path работает нормально (автономно). Однако они не собираются вместе. Любая помощь будет оценена!

Answer 1

Только форма элементов в <clipPath> имеет значение. Цвет и заливка игнорируются, поэтому вы не можете этого сделать.

Но вместо этого вы можете использовать <mask>:

<svg width='100' height='100' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="green"></stop> 
      <stop offset="100%" stop-color="yellow"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width=".1" height=".1"> 
      <circle cx="2" cy="2" r="2" fill="white"></circle> 
    </pattern> 
    <mask id="img-dotted-mask"> 
      <rect width="100" height="100" fill="url(#img-dotted-dots)"/> 
    </mask> 
  </defs> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path> 
</svg>

Источник: Combine clipPath, pattern, and linearGradient in SVG

Answer 2

Примеры анимации

Техника комбинации clipPath, pattern и linearGradient даёт широкий диапазон для творчества в веб строительстве.

  • Изменяя параметры width, height в pattern можно получить разные формы шаблона для заполнения фигур, а также горизонтальные и вертикальные полосы.

  • Применение различных команд анимации позволяет оживить картинку.

  • Добавляя текст можно получить дополнительные эффекты.

  • Добавление маски вместе с градиентом даёт возможность получить разноцветный круг с мягкими градиентными цветами.

Вертикальные полосы

Получаются за счет превышения ширины, в несколько раз, высоты в паттерне width="0.05" height="0.01"

Анимация полос достигается изменением радиуса окружности, входящей в паттерн:

<circle cx="2" cy="2" r="4" fill="white"> <animate attributeName="r" values="4;2;1;2;4;4" dur="8s" repeatCount="indefinite"/> </circle>

<svg width='200' height='200' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="greenyellow"></stop> 
      <stop offset="100%" stop-color="dodgerblue"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width="0.05" height="0.01"> 
      <circle cx="2" cy="2" r="4" fill="white"> 
	    <animate attributeName="r" values="4;2;1;2;4;4" dur="8s" repeatCount="indefinite"/> 
	  </circle> 
    </pattern> 
    <mask id="img-dotted-mask"> 
      <circle cx="50" cy="50" r="50" fill="url(#img-dotted-dots)"> 
	  <animate attributeName="cx1" values="50;175;50" dur="8s" repeatCount="indefinite"/>  
	   	 </circle>	 
    </mask> 
  </defs> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path> 
</svg> 

Горизонтальные полосы

Здесь у паттерна - width="0.005" height="0.05"> ширина меньше высоты

<svg width='200' height='200' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="greenyellow"></stop> 
      <stop offset="100%" stop-color="dodgerblue"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width="0.005" height="0.05"> 
      <circle cx="2" cy="2" r="4" fill="white"> 
	    <animate attributeName="r" values="4;2;1;2;4" dur="6s" repeatCount="indefinite"/> 
	  </circle> 
    </pattern> 
    <mask id="img-dotted-mask"> 
      <circle cx="50" cy="50" r="48"  fill="url(#img-dotted-dots)"> 
	  
	   	 </circle>	 
    </mask> 
  </defs> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path> 
</svg> 

Горизонтальные полосы в градиентном цветном круге

Добавляем к маске строку с шириной строки

<mask id="img-dotted-mask"> <circle cx="50" cy="50" r="48" stroke="dodgerblue" stroke-width="3" fill="url(#img-dotted-dots)"> </circle> </mask>

<svg width='200' height='200' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="greenyellow"></stop> 
      <stop offset="100%" stop-color="dodgerblue"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width="0.005" height="0.05"> 
      <circle cx="2" cy="2" r="4" fill="white"> 
	    <animate attributeName="r" values="4;2;1;2;4" dur="6s" repeatCount="indefinite"/> 
	  </circle> 
    </pattern> 
    <mask id="img-dotted-mask"> 
     <circle cx="50" cy="50" r="48" stroke="dodgerblue" stroke-width="3"  fill="url(#img-dotted-dots)"> </circle>	 
    </mask> 
  </defs> 
  <text font-size="18" x="20" y="50" fill="dodgerblue"> click me</text> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path> 
 </svg> 

Изменение размера фигур паттерна

Достигается изменением радиуса окружностей, входящих в паттерн

<circle cx="2" cy="2" r="4" fill="white"> <animate attributeName="r" values="4;2;1;2;4;4" dur="8s" repeatCount="indefinite"/>

<svg width='200' height='200' viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
  <defs> 
    <linearGradient id="img-dotted-gradient"> 
      <stop offset="0%" stop-color="greenyellow"></stop> 
      <stop offset="100%" stop-color="dodgerblue"></stop> 
    </linearGradient> 
    <pattern id="img-dotted-dots" x="0" y="0" width="0.05" height="0.05"> 
      <circle cx="2" cy="2" r="4" fill="white"> 
	    <animate attributeName="r" values="4;2;1;2;4;4" dur="8s" repeatCount="indefinite"/> 
	  </circle> 
    </pattern> 
    <mask id="img-dotted-mask"> 
      <circle cx="50" cy="50" r="50" fill="url(#img-dotted-dots)"></circle>	 
    </mask> 
  </defs> 
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" mask="url(#img-dotted-mask)"></path> 
</svg> 

READ ALSO
Как сделать эффект трещины у текста

Как сделать эффект трещины у текста

Данный Q-A является продолжением прошлого(стилизация текста SVG)

219
Как закрыть меню при клике на его пункт?

Как закрыть меню при клике на его пункт?

Добрый вечер, друзьяДля вступления хотел бы уточнить, что в js я пока полный ноль, только начинаю знакомится, поэтому прикреплю весь js прошлого...

182
Как передать данные таблицы html в функцию

Как передать данные таблицы html в функцию

Всем доброго времени сутокПроблема такая, у меня есть таблица html, нужно эту таблицу экспортировать в excel

175
Подписи к картинке в html

Подписи к картинке в html

Как реализовать такие подписи к картинке?

191