如何使SVG路径的笔划采用背景图像?

时间:2017-10-11 08:02:56

标签: javascript html css svg

我在SVG元素上使用动画(仅限路径)(只需使用JavaScript切换路径的visibility属性)。 SVG具有背景图像。显示的某些路径必须在笔划上具有背景图像(看起来好像它们是擦除路径)。我使用SVG的屏蔽功能来执行以下操作:



var t = 0;
var displayDictionary = {};

function fillDisplayDictionary()
{
  var paths = document.querySelectorAll("svg path");
 
  
  for(var index=0; index < paths.length; index++)
  {
    var path = paths[index];
    
    var pathDisplayTime = parseInt(path.getAttribute("data-t"));
    
    displayDictionary[pathDisplayTime] = path;
  }
  
}

function displayNextElement()
{
  displayDictionary[t].style.visibility = "visible";
  
  t++;
  
  if(t == 5)
    clearInterval(interval);
}



fillDisplayDictionary();
interval = setInterval(displayNextElement, 40);
&#13;
svg path
{
  visibility: hidden;
}
&#13;
<!DOCTYPE html>
<html>
<body>

<svg height="400" width="450">

<!-- this is the background image -->
<image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/Harry-Potter-1-.jpg" width="400" height="450"></image>
  
  <!-- these are ordinary paths -->
	<path data-t="0" d="M 100 350 l 150 -300" stroke="red" stroke-width="8" fill="none" />
  <path data-t="1" d="M 250 50 l 150 300" stroke="red" stroke-width="8" fill="none" />
  <path data-t="2" d="M 175 200 l 150 0" stroke="green" stroke-width="8" fill="none" />
  <path data-t="3" d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="8" fill="none" />
  
     
  <mask id="mask">
    <!-- this is the erasing path -->
    <path data-t="4" d="M 0 0 L 400 450" stroke="white" stroke-width="20"  />
  </mask>  
  
  <!-- this is an image identical to the background image, and it is masked by the above path-->
  <image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/Harry-Potter-1-.jpg" width="400" height="450" mask="url(#mask)"></image>
  
</svg>

</body>
</html>
&#13;
&#13;
&#13;

中风上有或没有背景图像的路径太多。这适用于Chrome。然而,在FireFox中,动画过程变得非常慢,同时显示擦除路径(即在笔划上具有背景图像的路径)。有没有其他方法可以显示Firefox响应良好的擦除路径。

1 个答案:

答案 0 :(得分:0)

您不需要使用屏蔽版图像进行透支。

只需将遮罩应用于线条。

&#13;
&#13;
<svg height="400" width="450">

<!-- this is the background image -->
<image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/Harry-Potter-1-.jpg" width="400" height="450"></image>
  
  <!-- these are ordinary paths -->
  <g mask="url(#mask)">
    <path data-t="0" d="M 100 350 l 150 -300" stroke="red" stroke-width="8" fill="none" />
    <path data-t="1" d="M 250 50 l 150 300" stroke="red" stroke-width="8" fill="none" />
    <path data-t="2" d="M 175 200 l 150 0" stroke="green" stroke-width="8" fill="none" />
    <path data-t="3" d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="8" fill="none" />
  </g>
     
  <mask id="mask">
    <!-- this is the erasing path -->
    <rect width="100%" height="100%" fill="white"/>
    <path data-t="4" d="M 0 0 L 400 450" stroke="black" stroke-width="20"  />
  </mask>  
  
</svg>
&#13;
&#13;
&#13;