5

Я пытаюсь создать фон, состоящий из градиента нескольких точек, от зеленого до желтого, слева направо. Поэтому идея заключалась в том, чтобы создать путь, заполнить его градиентом и 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 работает нормально (автономно). Однако они не собираются вместе.

Свободный перевод вопроса Combine clipPath, pattern, and linearGradient in SVG от участника @sdvnksv.

1

2 ответа 2

5

Только форма элементов в <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>

Свободный перевод ответа от участника @Paul LeBeau.

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"/>
</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.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> 

Ваш ответ

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

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