여기 각진 라인
에 어떤 각도에서 화살촉을 그릴 수있는 가장 쉬운 방법을 화살촉을 그리는 방법은 캔버스의이 기능을 회전 사용하는 것입니다.
Math.atan
함수를 사용하면 선의 경사에 따라 적절한 각도를 계산할 수 있습니다.
// calculate the radian angle of the line from [x1,y1] to [x2,y2]
var radianAngle=Math.atan((y2-y1)/(x2-x1));
// adjust the angle based on line slope
radianAngle+=((x2>x1)?90:-90)*Math.PI/180;
그럼 당신은 라인을 그릴 수
// draw the line
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
을 마지막으로 문맥을 돌려 화살표를 연결합니다.
// rotate the canvas context to the appropriate angle
ctx.rotate(radianAngle);
캔버스 자체를 회전 했으므로 화살촉을 수평 인 것처럼 그립니다. 단순한! 여기
// save the un-transformed state of the context
ctx.save();
ctx.beginPath();
// translate to the end of the line
ctx.translate(x2,y2);
// rotate to the appropriate angle
ctx.rotate(radianAngle);
// draw the arrowhead
ctx.moveTo(0,0);
ctx.lineTo(8,20);
ctx.lineTo(-8,20);
ctx.closePath();
ctx.fill();
// when done drawing on the rotated context, set it back to its untransformed state
ctx.restore();
입니다 코드와 바이올린 : http://jsfiddle.net/m1erickson/CQDww/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
function Line(x1,y1,x2,y2){
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
}
Line.prototype.drawWithArrowheads=function(ctx){
// arbitrary styling
ctx.strokeStyle="blue";
ctx.fillStyle="blue";
ctx.lineWidth=3;
// draw the line
ctx.beginPath();
ctx.moveTo(this.x1,this.y1);
ctx.lineTo(this.x2,this.y2);
ctx.stroke();
// draw the starting arrowhead
var startRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1));
startRadians+=((this.x2>this.x1)?-90:90)*Math.PI/180;
this.drawArrowhead(ctx,this.x1,this.y1,startRadians);
// draw the ending arrowhead
var endRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1));
endRadians+=((this.x2>this.x1)?90:-90)*Math.PI/180;
this.drawArrowhead(ctx,this.x2,this.y2,endRadians);
}
Line.prototype.drawArrowhead=function(ctx,x,y,radians){
ctx.save();
ctx.beginPath();
ctx.translate(x,y);
ctx.rotate(radians);
ctx.moveTo(0,0);
ctx.lineTo(8,20);
ctx.lineTo(-8,20);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// create a new line object
var line=new Line(50,50,150,150);
// draw the line
line.drawWithArrowheads(context);
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
나에게 너무 자세한 설명 주셔서 대단히 감사합니다, 저에게 많은 도움이! – user1151563