canvas 이용 머리쪽은 세모 아래쪽은 네모 대각선 그리기
- <!DOCTYPE html>
- <html>
- <head>
- <title> canvas 이용 화살표 있는 대각선 그리기</title>
- </head>
- <body>
- <div style="width:402px;height:402px;border:1px solid;">
- <div style="position:absolute;"><canvas id="lineDiv1" height="400" width="400"></canvas></div>
- </div>
- <script type="text/javascript">
- function ArrowLine(id){
- this.headSize=10;
- this.endSize=6;
- this.canvas=document.getElementById(id);
- this.ctx=this.canvas.getContext("2d");
- this.ctx.lineWidth=1;
- this.ctx.strokeStyle='blue';
- this.ctx.fillStyle='blue';
- // var gradient=this.ctx.createLinearGradient(0,0,170,0);
- // gradient.addColorStop("0","red");
- // gradient.addColorStop("0.5","magenta");
- // gradient.addColorStop("1.0","blue");
- // this.ctx.strokeStyle=gradient;
- // this.ctx.fillStyle=gradient;
- };
- ArrowLine.prototype.draw=function(x1,y1,x2,y2){
- // draw the line
- this.ctx.beginPath();
- this.ctx.moveTo(x1,y1);
- this.ctx.lineTo(x2,y2);
- this.ctx.stroke();
- var radians = Math.atan((y2-y1)/(x2-x1));
- //Head
- headRadians = radians + ((x2>x1)?-90:90)*Math.PI/180;
- this.drawhead(this.ctx,x1,y1,headRadians);
- //End
- endRadians = radians + ((x2>x1)?90:-90)*Math.PI/180;
- this.drawEnd(this.ctx,x2,y2,endRadians);
- };
- ArrowLine.prototype.drawhead=function(ctx,x,y,radians){
- ctx.save();
- ctx.beginPath();
- ctx.translate(x,y);
- ctx.rotate(radians);
- ctx.moveTo(0,0);
- ctx.lineTo(5,this.headSize);
- ctx.lineTo(-5,this.headSize);
- ctx.closePath();
- ctx.restore();
- ctx.fill();
- };
- ArrowLine.prototype.drawEnd=function(ctx,x,y,radians){
- ctx.save();
- ctx.beginPath();
- ctx.translate(x,y);
- ctx.rotate(radians);
- ctx.moveTo(0,0);
- ctx.lineTo(-this.endSize,0);
- ctx.lineTo(this.endSize,0);
- ctx.lineTo(this.endSize,-this.endSize);
- ctx.lineTo(-this.endSize,-this.endSize);
- ctx.lineTo(-this.endSize,0);
- ctx.closePath();
- ctx.restore();
- ctx.fill();
- };
- var ArrowLine=new ArrowLine("lineDiv1");
- ArrowLine.draw(45,90,250,275);
- </script>
- </body>
- </html>
원본 참고 자료
http://stackoverflow.com/questions/16025326/html-5-canvas-complete-arrowhead
http://jsfiddle.net/m1erickson/Sg7EZ/