Intersecting paths in Raphael
I am trying to found out if two paths are intersected in Raphael. I have tried getBBox() but that returns the coo开发者_如何学编程rdinates of a box around the path itself. Is there an easier way to achieve this?
The previous answers may have been for an earlier version of Raphael. The API now includes a pathIntersection method which returns an array of intersecting points. You can simply check the length of the return value.
Bruteforce method. Get all the points for the two path and see if two points are the same.
I made you this but maybe you should come up with a better comparing solution. Depending on how long your paths are, this can be heavy.
var paper = Raphael(0, 0, '100%', '100%');
var path1 = paper.path("M0 0L100 100");
var path2 = paper.path("M100 0L0 100");
var array1 = new Array();
var array2 = new Array();
for(var i = 0; i < path1.getTotalLength(); i++) {
array1.push(path1.getPointAtLength(i));
}
for(var i = 0; i < path2.getTotalLength(); i++) {
array2.push(path2.getPointAtLength(i));
}
for(var i = 0; i < array1.length; i++) {
for(var k = 0; k < array2.length; k++) {
// the threshold +-1 is important!
if(array1[i].x < ( array2[k].x + 1 ) &&
array1[i].x > ( array2[k].x - 1 )) {
if(array1[i].y < ( array2[k].y + 1 ) &&
array1[i].y > ( array2[k].y - 1 )) {
alert('yeah'); // uncomment this. It will alert 4 times.
}
}
}
}
I guess you need to implement something yourself as it seems Raphael doesn't provide this sort of functionality. Here's a circle intersection example that might help. Here's something more specific.
Before running your actual algo you probably want to check if the bounding boxes intersect. If they do, check actual paths.
Use this lovely intersection library. With that you can do stuff like this:
var shape1 = new Path(pathElement1),
shape2 = new Path(pathElement2);
var inter = Intersection.intersectShapes(shape1, shape2);
if(inter.points.length > 0) {
// yes they intersect!
}
The inter
object in my example contains other good stuff to.
精彩评论