Extend SVG Mask without stretching?

2019-07-27 09:26发布

I'm trying to produce a "light source" effect within SVG, whereby I cut out a section of darkness that will cover an image. I've almost got what I need, but I'm struggling to work out how to finish off the last piece. First here's my example of where I've got to

.background {
  width: 500px;
  height: 500px;
  background: red;
}

.light {
  fill: black;
}
<div class="background">
  <svg width="500" height="500">
    <defs>
      <radialGradient id="radGrad">
        <stop offset="0" stop-color="white" stop-opacity="0" />
        <stop offset="1" stop-color="white" stop-opacity="1" />
      </radialGradient>
      <mask id="hole">
        <rect x="0" y="0" width="500" height="500" fill="black"></rect>
        <circle cx="250" cy="250" r="155" fill="url(#radGrad)" />
      </mask>
    </defs>
    <rect class="light" x="0" y="0" width="500" height="500" mask="url(#hole)"></rect>
  </svg>
</div>

What I want to do now, is to extend the black fill to the rest of the SVG, but maintain the radial gradient size. I just can't seem to work out how to do it. In fact the additional <rect> within the <mask> that I forgot to take out is my attempt at doing so.

The affect I'm trying to get is:

enter image description here

But so far the nearest I've got is by increasing the radius of the circle, however then this increases the area of transparency which isn't what I want. Am I missing something really simple here?

标签: html svg
1条回答
一夜七次
2楼-- · 2019-07-27 10:16

Just apply the gradient to the rectangle. No need for an extra circle.

You just need to tweak your gradient a bit.

.background {
  width: 500px;
  height: 500px;
  background: red;
}

.light {
  fill: black;
}
<div class="background">
  <svg width="500" height="500">
    <defs>
      <radialGradient id="radGrad" r="0.31">
        <stop offset="0" stop-color="black" />
        <stop offset="1" stop-color="white" />
      </radialGradient>
      <mask id="hole">
        <rect x="0" y="0" width="500" height="500" fill="url(#radGrad)" />
      </mask>
    </defs>
    <rect class="light" x="0" y="0" width="500" height="500" mask="url(#hole)" />
  </svg>
</div>

查看更多
登录 后发表回答