2016-06-22 137 views
0

在我的应用程序中,使用图像掩盖SVG图形比使用其他方法更方便。 (所需的多色叠加效果可以通过任何方式实现。)问题是,当我使用普通(灰度)图像作为蒙版时,结果看起来像是负片。是否有一个SVG属性或聪明的JS/D3技巧,我可以用它来告诉浏览器颠倒它的遮罩协议,还是我坚持自己转换图像(这可能最终不如另一种方式)?反转SVG图像蒙版

更新小例子:

<!DOCTYPE html> 
 
<title>Image mask</title> 
 

 
<script type="text/javascript" 
 
    src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"> 
 
</script> 
 
<body> 
 
<div> 
 
<button>toggle</button> 
 
</div> 
 
</body> 
 
<script> 
 
var width = 194, 
 
\t height = 240; 
 
\t maskWidth = 30; 
 
var svg = d3.select('body').append('svg') 
 
\t .attr('height', 500); 
 

 
var myMask = svg.insert('mask', ':first-child') 
 
\t .attr('id', 'image_mask'); 
 

 
var marilyn = myMask.append('image') 
 
\t .attr('width', width) 
 
\t .attr('height', height) 
 
\t .attr('xlink:href', "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Marilyn_Monroe_photo_pose_Seven_Year_Itch.jpg/194px-Marilyn_Monroe_photo_pose_Seven_Year_Itch.jpg"); 
 

 
var positive = svg.append('rect') 
 
\t .attr('width',maskWidth) 
 
\t .attr('height', height) 
 
\t .attr('fill', 'red') 
 
\t .attr('mask', 'url(#image_mask)'); 
 

 
var negative = svg.append('rect') 
 
\t .attr('x', maskWidth) 
 
\t .attr('width', width - maskWidth) 
 
\t .attr('height', height) 
 
\t .attr('fill', 'green') 
 
\t .attr('mask', 'url(#image_mask)'); 
 
\t 
 
var toggle = false; 
 
d3.select('button').on('click', function() { 
 
\t toggle = !toggle; 
 
\t positive.transition() 
 
\t \t .attr('height', toggle ? height/2 : height); 
 
}); 
 

 
</script>

+0

您可以用SVG滤镜做伟大的事情 - 请把你的适应 –

+0

代码@MichaelMullany好啦,我已经发布了一个小例子。 – bongbang

回答

2

你需要使用<filter>反转在你的面具的形象。

<svg height="500" xmlns:xlink="http://www.w3.org/1999/xlink" > 
 
    <defs> 
 
    <filter id="invert"> 
 
     <feComponentTransfer> 
 
     <feFuncR type="table" tableValues="1 0"/> 
 
     <feFuncG type="table" tableValues="1 0"/> 
 
     <feFuncB type="table" tableValues="1 0"/> 
 
     </feComponentTransfer> 
 
    </filter> 
 
    <mask id="image_mask"> 
 
     <image width="194" height="240" xlink:href="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Marilyn_Monroe_photo_pose_Seven_Year_Itch.jpg/194px-Marilyn_Monroe_photo_pose_Seven_Year_Itch.jpg" 
 
      filter="url(#invert)"/> 
 
    </mask> 
 
    </defs> 
 
    
 
    <rect width="30" height="120" fill="red" mask="url(#image_mask)"/> 
 
    <rect x="30" width="164" height="240" fill="green" mask="url(#image_mask)"/> 
 
</svg>