使用JavaScript检测已关闭的SVG多边形内部

时间:2015-10-06 19:30:36

标签: javascript svg point-in-polygon

在准系统测试中,我创建了一个SVG五边形,其矩形与其完全吻合。我运行svg.checkIntersection(pentagon, rect)来测试1x1 rect是否在五角大楼区域内。

这将返回五角形边界矩内任意点的true。我怎样才能让它返回false,除非该点实际上在五边形内部?

这是我的HTML代码:

<!DOCTYPE html>
<html lang=en>
<head>
  <meta charset="utf-8">
  <title>Hit SVG</title> 
</head>
<body>
<!-- Pentagon with a side of 100px -->
<svg xmlns="http://www.w3.org/2000/svg"
     style="display: none;">
  <symbol id="pentagon">
    <polygon
points="
80.9016994375,0
0,58.7785252292
30.9016994375,153.8841768588
130.9016994375,153.8841768588
161.8033988750,58.7785252292
"
style="stroke: #eee"></polygon>
  </symbol>
</svg>

<!-- Rectangle with a golden ratio -->
<svg class="container" width="324" height="308" onclick="hitTest(event)">
  <rect width="324" height="308" style="fill: #ccc"></rect>
  <rect width="162" height="154" style="fill: #999"></rect>

  <svg style="fill:#333" viewBox="0 0 162 154", width="162" height="154">
    <use xlink:href="#pentagon"></use>
  </svg>
</svg>

<script>
function hitTest(event) {
  var svg = event.currentTarget
  var pentagon = document.querySelector("use")

  var rect = svg.createSVGRect()
  rect.x = event.offsetX
  rect.y = event.offsetY
  rect.width = rect.height = 1
  hit = svg.checkIntersection(pentagon, rect)
  console.log(hit)
}
</script>
</body>

http://jsfiddle.net/nv5ndt4q/

0 个答案:

没有答案