Combine clipPath, pattern, and linearGradient in SVG

蓝咒 提交于 2021-02-19 03:56:50

问题


I am trying to create a background that consists of multiple dots gradienting from say green to yellow from left to right. So they idea was to create a path, fill it with a gradient and clip path with a pattern:

https://codepen.io/Deka87/pen/pLPqJE?editors=1000

<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>
  </defs>
  <path d="M0 0 H 100 V 100 H 0 Z" fill="url(#img-dotted-gradient)" clip-path="url(#img-dotted-dots)"></path>
</svg>

The gradient works OK, the clip path works OK (standalone). However they don't come together. Any help would be appreciated!


回答1:


Only the shape of the elements in a <clipPath> matter. The colour and fill are ignored, so you can't do it that way.

But you can use a <mask> instead.

<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>


来源:https://stackoverflow.com/questions/49427368/combine-clippath-pattern-and-lineargradient-in-svg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!