SVG文本填充未填充指定的颜色

时间:2020-05-06 21:31:14

标签: html css svg

我有一个SVG文本和一个蒙版(稍后对蒙版进行动画处理),我最初希望填充白色。但是,当我将填充设置为白色时,文本会丢失,就像颜色是透明的一样。这是相关的代码...

svg {
  margin: 0;
  color: rgba(255, 255, 255, 1);
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
}

rect {
  -webkit-mask: url(#mask);
  mask: url(#mask);
  fill: #f00;
}

defs {
  mask {
    text {
      font-size: 8vw;
      /* Using black to illustrate text fill isn't updating */
      fill: #000;
    }
  }
}

#editText {
  @media screen and (max-width: 480px) {
    transform: translateY(-10%);
  }
}
<svg preserveAspectRatio="xMinYMin meet">
  <defs>
    <mask id="mask" x="0" y="0" width="100%" height="100%">
      <rect x="0" y="0" width="100%" height="100%"></rect>
      <text x="50%" y="50vh" text-anchor="middle">
        Text line 1
      </text>
      <text
        id="editText"
        x="50%"
        y="65vh"
        text-anchor="middle"
      >
        Text line 2
      </text>
    </mask>
  </defs>
  <rect x="0" y="0" width="100%" height="100%"></rect>
</svg>

这是本地的样子... How it currently looks

这是它的外观(用白色文本代替透明)

how it should look

我在文本元素上尝试了笔画,颜色和渐变的组合,但是没有运气。关于我要去哪儿有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果我的理解正确,您想使用遮罩对文本形状的矩形进行切割,以便您可以看到该切口下方的内容。如果是这样,我看到的主要问题是使用css选择器。页面中的所有rect元素都有一个选择器,其中包括掩码的元素。我认为您需要确保仅影响要影响的元素。例如,您可以使用idclass选择器:

svg {
  margin: 0;
  color: rgba(255, 255, 255, 1);
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
}

#background{
  fill: #ff0;
}

#outrect {
  -webkit-mask: url(#mask);
  mask: url(#mask);
  fill: #f00;
}

.masktext{
  stroke: #000;
}
#maskrect{
  fill: #fff;
}

#editText {
  @media screen and (max-width: 480px) {
    transform: translateY(-10%);
  }
}
<svg preserveAspectRatio="xMinYMin meet">
  <defs>
    <mask id="mask" x="0" y="0" width="100%" height="100%">
      <rect id="maskrect" x="0" y="0" width="100%" height="100%"></rect>
      <text class="masktext" x="50%" y="50vh" text-anchor="middle">
        Text line 1
      </text>
      <text
        id="editText"
        class="masktext"
        x="50%"
        y="65vh"
        text-anchor="middle"
      >
        Text line 2
      </text>
    </mask>
  </defs>
  <rect id="background" x="0" y="0" width="100%" height="100%"></rect>
  <rect id="outrect" x="0" y="0" width="100%" height="100%"></rect>
</svg>

我还在下方的 中添加了一个黄色矩形,以查看其透明度。现在,您可以通过更改.masktext#maskrect的颜色来调节透明度。