如何检查中风是否穿过任何其他中风?这可能吗?
我尝试使用ispointInPath()
和ispointInStroke()
,但它不起作用。
答案 0 :(得分:0)
如果两个笔划都是线段,你可以使用Paul Bourke的测试来测试它们是否相交:
// Get interseting point of 2 line segments (if any)
// Attribution: http://paulbourke.net/geometry/pointlineplane/
function line2lineIntersection(p0,p1,p2,p3) {
var unknownA = (p3.x-p2.x) * (p0.y-p2.y) - (p3.y-p2.y) * (p0.x-p2.x);
var unknownB = (p1.x-p0.x) * (p0.y-p2.y) - (p1.y-p0.y) * (p0.x-p2.x);
var denominator = (p3.y-p2.y) * (p1.x-p0.x) - (p3.x-p2.x) * (p1.y-p0.y);
// Test if Coincident
// If the denominator and numerator for the ua and ub are 0
// then the two lines are coincident.
if(unknownA==0 && unknownB==0 && denominator==0){return(null);}
// Test if Parallel
// If the denominator for the equations for ua and ub is 0
// then the two lines are parallel.
if (denominator == 0) return null;
// If the intersection of line segments is required
// then it is only necessary to test if ua and ub lie between 0 and 1.
// Whichever one lies within that range then the corresponding
// line segment contains the intersection point.
// If both lie within the range of 0 to 1 then
// the intersection point is within both line segments.
unknownA /= denominator;
unknownB /= denominator;
var isIntersecting=(unknownA>=0 && unknownA<=1 && unknownB>=0 && unknownB<=1)
if(!isIntersecting){return(null);}
return({
x: p0.x + unknownA * (p1.x-p0.x),
y: p0.y + unknownA * (p1.y-p0.y)
});
}
否则,您可以使用像素命中测试来测试一个笔划是否与任何其他笔划相交:
context.getImageData
获取两幅画布的像素数据。
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var cw=canvas1.width;
var ch=canvas1.height;
// draw test stroke on canvas#1
ctx1.beginPath();
ctx1.arc(150,100,50,0,Math.PI);
ctx1.lineWidth=3;
ctx1.stroke();
// draw target stroke on canvas#2
ctx2.beginPath();
ctx2.arc(150,175,50,0,Math.PI,true);
ctx2.lineWidth=3;
ctx2.strokeStyle='red';
ctx2.stroke();
// report if the target stroke intersects with any other stroke
alert('Assert: The red target intersects any other stroke: '+intersects());
function intersects(){
// get the pixel data for both canvases
var data1=ctx1.getImageData(0,0,cw,ch).data;
var data2=ctx2.getImageData(0,0,cw,ch).data;
// test all corresponding pixels
// data[i+3] is the opacity value so if both data[i+3]'s are
// non-zero, then both canvases have strokes at that pixel
for(var i=0;i<data1.length;i+=4){
if(data1[i+3]>0 && data2[i+3]>0){
return(true);
}
}
return(false);
}
&#13;
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
&#13;
<h4>The Other stroke(s)</h4>
<canvas id="canvas1" width=300 height=300></canvas>
<h4>The target stroke to test if it overlaps others</h4>
<canvas id="canvas2" width=300 height=300></canvas>
&#13;