javascript - 使用 svg 的透明渐变蒙版

标签 javascript html css svg

我需要一些关于 svg 的帮助。有一个“背景图像”。另一个“图像”覆盖在​​它上面。 “图像”必须切出一个孔,以便背景图像能透过。我通过使用 svg 实现了这一点:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
<title>Title of the document</title>
<style>
  body{
    background-repeat: no-repeat;
    background-size: cover;
  }
   #svg-door {
    background-image: url(http://pcdn.500px.net/15548893/7f3b7c411716b1fb29c5cffb3efcf8ce33eacd76/15.jpg);
    background-size: cover;
    box-sizing: border-box;
    padding: 100px;
    width: 100%;
    height: 500px;
  }
  #wood {
    border-radius: 50%;
  }
</style>
  </head>
 <body background="https://www.w3schools.com/css/img_fjords.jpg" >
<svg xmlns="http://www.w3.org/2000/svg" id="svg-door">
  <defs>
    <pattern id="wood" patternUnits="userSpaceOnUse" width="1024" height="768">
      <image xlink:href="http://i.imgur.com/Ljug3pp.jpg" x="0" y="0" width="1024" height="768"/>
    </pattern>
  </defs>
  <path xmlns="http://www.w3.org/2000/svg" d=" M0,0 225,0 225,300 0,300 z M105,50, 180,50 180,80 105,80 z "
        fill="url(#wood)" fill-rule="evenodd"/>
</svg>
</body>

由于浏览器兼容性原因,我无法使用 css 的掩码过滤器。我不想使用 svg/js 框架。

到目前为止一切顺利。现在我想更进一步。

我希望这个洞有一个透明的渐变。这样内部矩形边界就不像当前版本那么硬了。我不知道该怎么做。

此外,我想为这个洞制作动画,使其随着时间的推移变得更大。我会用js来做。还有别的办法吗?也许通过改变 html 的整个结构?

感谢任何帮助。

最佳答案

首先,应用于 SVG 元素的 mask 应该没有问题。有一些浏览器兼容性与应用于 HTML 元素的 SVG 掩码有关,但当它们应用于 SVG 元素时则不然。

事实上,面具是解决您问题的明显方法。为了使孔的边缘柔和,我们将对矩形应用模糊滤镜,然后将其用作 mask 来创建孔。

  body{
    background-repeat: no-repeat;
    background-size: cover;
  }
   #svg-door {
    background-image: url(http://pcdn.500px.net/15548893/7f3b7c411716b1fb29c5cffb3efcf8ce33eacd76/15.jpg);
    background-size: cover;
    box-sizing: border-box;
    padding: 100px;
    width: 100%;
    height: 500px;
  }
  #wood {
    border-radius: 50%;
  }
<
<body background="https://www.w3schools.com/css/img_fjords.jpg" >

<svg xmlns="http://www.w3.org/2000/svg" id="svg-door">
  <defs>
    <pattern id="wood" patternUnits="userSpaceOnUse" width="1024" height="768">
      <image xlink:href="http://i.imgur.com/Ljug3pp.jpg" x="0" y="0" width="1024" height="768"/>
    </pattern>
    
    <mask id="hole">
      <rect width="100%" height="100%" fill="white"/>
      <path d="M105,50, 180,50 180,80 105,80 z" filter="url(#hole-blur)"/>
    </mask>

    <filter id="hole-blur">
      <feGaussianBlur stdDeviation="2"/>
    </filter>
  </defs>

  <path d="M0,0 225,0 225,300 0,300 z" fill="url(#wood)" mask="url(#hole)"/>
</svg>

</body>

关于javascript - 使用 svg 的透明渐变蒙版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45432753/

相关文章:

javascript - 使用正则表达式提取单词

javascript - 如何使svg组中的所有元素改变颜色onclick(js)

javascript - 使用自定义原型(prototype)实例化 JavaScript 函数

javascript - 在各种平台(例如智能手机、平板电脑)上保持 div 的大小

PHP 代码无法在 HTML 中运行

html - li 面包屑图片定位错误

html - 悬停每个元素时如何突出显示所有匹配的元素?

javascript - 如果 jquery 返回未定义并且不工作

javascript - 为什么不能通过数据绑定(bind)分配元素的类?

html - 什么更容易访问,文本缩进 : -9999px or just using an img with an alt tag?