<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/0.11.1/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Line Polygon Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="script.js"></script>
</body>
</html>
function isInside(point, vertices) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var i, j, xi, xj, yi, yj, intersect,
x = point.x,
y = point.y,
inside = false;
for (i = 0, j = vertices.length - 1; i < vertices.length; j = i, i += 1) {
xi = vertices[i].x;
yi = vertices[i].y;
xj = vertices[j].x;
yj = vertices[j].y;
intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) {
inside = !inside;
}
}
return inside;
}
// Code goes here
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var poly = new Konva.Line({
points: [23, 20, 23, 160, 70, 93, 150, 109, 290, 139, 270, 93],
fill: 'rgba(111,111,111,0.5)',
stroke: 'black',
strokeWidth: 5,
closed: true,
draggable: true
});
var blueCircle = new Konva.Circle({
x: 50,
y: 50,
draggable: true,
fill: 'blue',
stroke: 'black',
radius: 10
});
var redCircle = new Konva.Circle({
x: 150,
y: 150,
draggable: true,
fill: 'red',
stroke: 'black',
radius: 10
});
poly.on('dragmove', function(e) {
});
poly.on('dragend', function(e) {
var vs = [],
//getting line point but don't know why always get same point.
points = poly.getPoints();
for (var i = 0; i < points.length; i += 2) {
vs.push({
x: points[i],
y: points[i + 1]
});
}
console.log('Blue, isInside: ' + isInside(blueCircle.getPosition(), vs));
console.log('Red, isInside: ' + isInside(redCircle.getPosition(), vs));
//same points after drag
console.log('Same points after drag ',points);
});
layer.add(blueCircle);
layer.add(redCircle);
// add the shape to the layer
layer.add(poly);
// add the layer to the stage
stage.add(layer);
/* Styles go here */