SVG Mask 使线条消失
SVG Mask makes line disappear
在我下面的示例中,蒙版在绿线和蓝线上正常工作,但使水平红线完全消失。摘下面具后,红线似乎没什么问题。怎么回事?
document.querySelector('button').addEventListener('click', function(){
document.getElementById('problem-line').removeAttribute('mask')
}, false)
<svg width="400" height="180">
<defs>
<g id='circle'>
<circle r="50" cx="100" cy="100" />
</g>
<mask id="hole">
<rect width="100%" height="100%" fill="white" />
<use xlink:href="#circle" />
</mask>
</defs>
<use xlink:href="#circle" opacity='0.5' />
<line id='problem-line' x1='100' y1='100' x2='300' y2='100' stroke='red' mask="url(#hole)" />
<line x1='100' y1='100' x2='300' y2='50' stroke='green' mask="url(#hole)" />
<line x1='100' y1='100' x2='300' y2='150' stroke='blue' mask="url(#hole)" />
</svg>
<div>
<button>Remove mask</button>
</div>
maskUnits is objectBoundingBox. The key issue you have is described in the last paragraph of the specification text 的默认值。
Keyword objectBoundingBox should not be used when the geometry of the applicable element has no width or no height, such as the case of a horizontal or vertical line, even when the line has actual thickness when viewed due to having a non-zero stroke width since stroke width is ignored for bounding box calculations. When the geometry of the applicable element has no width or height and objectBoundingBox is specified, then the given effect (e.g., a gradient or a filter) will be ignored.
如果你有一条水平线,为什么不使用带填充的矩形而不是带笔划的线?或者使用 userSpaceOnUse 单位。
在我下面的示例中,蒙版在绿线和蓝线上正常工作,但使水平红线完全消失。摘下面具后,红线似乎没什么问题。怎么回事?
document.querySelector('button').addEventListener('click', function(){
document.getElementById('problem-line').removeAttribute('mask')
}, false)
<svg width="400" height="180">
<defs>
<g id='circle'>
<circle r="50" cx="100" cy="100" />
</g>
<mask id="hole">
<rect width="100%" height="100%" fill="white" />
<use xlink:href="#circle" />
</mask>
</defs>
<use xlink:href="#circle" opacity='0.5' />
<line id='problem-line' x1='100' y1='100' x2='300' y2='100' stroke='red' mask="url(#hole)" />
<line x1='100' y1='100' x2='300' y2='50' stroke='green' mask="url(#hole)" />
<line x1='100' y1='100' x2='300' y2='150' stroke='blue' mask="url(#hole)" />
</svg>
<div>
<button>Remove mask</button>
</div>
maskUnits is objectBoundingBox. The key issue you have is described in the last paragraph of the specification text 的默认值。
Keyword objectBoundingBox should not be used when the geometry of the applicable element has no width or no height, such as the case of a horizontal or vertical line, even when the line has actual thickness when viewed due to having a non-zero stroke width since stroke width is ignored for bounding box calculations. When the geometry of the applicable element has no width or height and objectBoundingBox is specified, then the given effect (e.g., a gradient or a filter) will be ignored.
如果你有一条水平线,为什么不使用带填充的矩形而不是带笔划的线?或者使用 userSpaceOnUse 单位。