I want to draw two lines that go through three points, and make a rounded corner at the second point. Here I have a problem. If the angle between the two lines is less than 90 degrees, there will be an extra line appended on the line through point1 and point2. If the angle is larger than or equal to 90 degrees, it will be ok, though.
You can see this in the snippet below:
function Point(x, y){
this.x = x ? x : 0;
this.y = y ? y : 0;
}
var ctx,
canvas = document.getElementById('canvas');
canvas.width = 600;
canvas.height = 600;
ctx = canvas.getContext('2d');
ctx.lineWidth = 2;
draw(ctx, new Point(50,10), new Point(20, 300), new Point(100, 320) );
draw(ctx, new Point(200,10), new Point(200, 300), new Point(300, 20) );
function draw(ctx, p1, p2, p3){
var k1,k2, k, len, r=8;
k1 = Math.atan2(p2.y - p1.y, p2.x - p1.x);
k2 = Math.atan2(p3.y - p2.y, p3.x - p2.x);
k = (k1-k2)/2;
len = Math.abs(r/Math.tan(k)); // the distance between point of tangency and p2
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x - len*Math.cos(k1), p2.y - len*Math.sin(k1) ); // lineTo the point of tangency
ctx.arcTo(p2.x, p2.y, p2.x + len*Math.cos(k2), p2.y + len*Math.sin(k2), r ); // then arc
ctx.lineTo(p3.x, p3.y); // till p3
ctx.stroke();
}
<canvas id='canvas' style="width:600px; height:600px; margin: 0 auto; background-color: yellow; "; />
I couldn’t find your error so started again see http://jsfiddle.net/yUkK3/6/
Seems to work OK unless you have P1 and P3 in wrong order. (Last example on the fiddle) Can see why it happens but have not worked on correction yet.
Explanation of when it goes wrong.
Taking P2 as origin, rotate P1 so that P1 to P2 lies along x axis with P1 positive, then drawing fails when P3.y is negative.
Hope this helps
EDIT Have now sorted out the order problem described above. http://jsfiddle.net/yUkK3/7/