【问题标题】:Inverting SVG image mask反转 SVG 图像蒙版
【发布时间】:2016-06-23 14:15:01
【问题描述】:

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

更新小例子:

<!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,
	height = 240;
	maskWidth = 30;
var svg = d3.select('body').append('svg')
	.attr('height', 500);

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

var marilyn = myMask.append('image')
	.attr('width', width)
	.attr('height', height)
	.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')
	.attr('width',maskWidth)
	.attr('height', height)
	.attr('fill', 'red')
	.attr('mask', 'url(#image_mask)');

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

</script>

【问题讨论】:

  • 你可以用 SVG 过滤器做很多事情 - 请发布你的代码以适应
  • @MichaelMullany 好的,我已经发布了一个最小的示例。

标签: html d3.js svg


【解决方案1】:

您需要使用&lt;filter&gt; 来反转蒙版中的图像。

<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>

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 2016-10-24
    • 2014-10-15
    • 2020-03-24
    • 2015-01-12
    • 2011-03-16
    • 2017-07-03
    相关资源
    最近更新 更多