Reputation: 5330
i have four divs that is p1,p2,p3,p4. it is draggable. at any point i click "draw" button iwant to draw angle sign like below
$(document).ready(function(){
var c=document.getElementById('canvas');
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(parseInt($("#p1").css("left"))-5,parseInt($("#p1").css("top"))-5)
ctx.lineTo(parseInt($("#p2").css("left"))-5,parseInt($("#p2").css("top"))-5)
ctx.lineTo(parseInt($("#p3").css("left"))-5,parseInt($("#p3").css("top"))-5)
ctx.lineTo(parseInt($("#p4").css("left"))-5,parseInt($("#p4").css("top"))-5)
ctx.lineTo(parseInt($("#p1").css("left"))-5,parseInt($("#p1").css("top"))-5)
ctx.fillStyle='#E6E0EC';
ctx.fill();
ctx.strokeStyle="#604A7B";
ctx.lineWidth="3"
ctx.stroke();
ctx.closePath();
$("#p1,#p2,#p3,#p4").draggable({
drag:function(){
ctx.clearRect(0,0,500,500);
ctx.beginPath();
ctx.moveTo(parseInt($("#p1").css("left"))-5,parseInt($("#p1").css("top"))-5)
ctx.lineTo(parseInt($("#p2").css("left"))-5,parseInt($("#p2").css("top"))-5)
ctx.lineTo(parseInt($("#p3").css("left"))-5,parseInt($("#p3").css("top"))-5)
ctx.lineTo(parseInt($("#p4").css("left"))-5,parseInt($("#p4").css("top"))-5)
ctx.lineTo(parseInt($("#p1").css("left"))-5,parseInt($("#p1").css("top"))-5)
ctx.fillStyle='#E6E0EC';
ctx.fill();
ctx.strokeStyle="#604A7B";
ctx.lineWidth="3"
ctx.stroke();
ctx.closePath();
}
});
How can i make this please provide simple solution.
the fiddle:http://jsfiddle.net/b954W/
i want to draw the arc inside the shape at any point.
Upvotes: 0
Views: 3880
Reputation: 105015
Here's how to illustrate the angle between line segments
Demo: http://jsfiddle.net/m1erickson/XnL3B/
Step#1: Calculate the angles
You can calculate the angle between 2 lines connected at a vertex using Math.atan2:
// calculate the angles in radians using Math.atan2
var dx1=pt1.x-pt2.x;
var dy1=pt1.y-pt2.y;
var dx2=pt3.x-pt2.x;
var dy2=pt3.y-pt2.y;
var a1=Math.atan2(dy1,dx1);
var a2=Math.atan2(dy2,dx2);
Step#2: Draw the angle's wedge
You can draw the wedge illustrating the angle using context.arc:
// draw angleSymbol using context.arc
ctx.save();
ctx.beginPath();
ctx.moveTo(pt2.x,pt2.y);
ctx.arc(pt2.x,pt2.y,20,a1,a2);
ctx.closePath();
ctx.fillStyle="red";
ctx.globalAlpha=0.25;
ctx.fill();
ctx.restore();
Step#3: Draw the degree angle in text
And you can draw the text of the angle (converted to degrees) using context.fillText:
// draw the degree angle in text
var a=parseInt((a2-a1)*180/Math.PI+360)%360;
ctx.fillStyle="black";
ctx.fillText(a,pt2.x+15,pt2.y);
Upvotes: 1