'Canvas'에 해당되는 글 1건

  1. 2014.09.27 [HTML5] canvas 이용 화살표 있는 대각선 그리기
Programming/HTML/CSS2014. 9. 27. 16:14

canvas 이용 머리쪽은 세모 아래쪽은 네모 대각선 그리기


  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title> canvas 이용 화살표 있는 대각선 그리기</title>
  5. </head>
  6. <body>
  7. <div style="width:402px;height:402px;border:1px solid;">
  8. <div style="position:absolute;"><canvas id="lineDiv1" height="400" width="400"></canvas></div>
  9. </div>
  10. <script type="text/javascript">
  11. function ArrowLine(id){
  12. this.headSize=10;
  13. this.endSize=6;
  14. this.canvas=document.getElementById(id);
  15. this.ctx=this.canvas.getContext("2d");
  16. this.ctx.lineWidth=1;
  17. this.ctx.strokeStyle='blue';
  18. this.ctx.fillStyle='blue';
  19. // var gradient=this.ctx.createLinearGradient(0,0,170,0);
  20. // gradient.addColorStop("0","red");
  21. // gradient.addColorStop("0.5","magenta");
  22. // gradient.addColorStop("1.0","blue");
  23. // this.ctx.strokeStyle=gradient;
  24. // this.ctx.fillStyle=gradient;
  25. };
  26. ArrowLine.prototype.draw=function(x1,y1,x2,y2){
  27. // draw the line
  28. this.ctx.beginPath();
  29. this.ctx.moveTo(x1,y1);
  30. this.ctx.lineTo(x2,y2);
  31. this.ctx.stroke();
  32. var radians = Math.atan((y2-y1)/(x2-x1));
  33. //Head
  34. headRadians = radians + ((x2>x1)?-90:90)*Math.PI/180;
  35. this.drawhead(this.ctx,x1,y1,headRadians);
  36. //End
  37. endRadians = radians + ((x2>x1)?90:-90)*Math.PI/180;
  38. this.drawEnd(this.ctx,x2,y2,endRadians);
  39. };
  40. ArrowLine.prototype.drawhead=function(ctx,x,y,radians){
  41. ctx.save();
  42. ctx.beginPath();
  43. ctx.translate(x,y);
  44. ctx.rotate(radians);
  45. ctx.moveTo(0,0);
  46. ctx.lineTo(5,this.headSize);
  47. ctx.lineTo(-5,this.headSize);
  48. ctx.closePath();
  49. ctx.restore();
  50. ctx.fill();
  51. };
  52. ArrowLine.prototype.drawEnd=function(ctx,x,y,radians){
  53. ctx.save();
  54. ctx.beginPath();
  55. ctx.translate(x,y);
  56. ctx.rotate(radians);
  57. ctx.moveTo(0,0);
  58. ctx.lineTo(-this.endSize,0);
  59. ctx.lineTo(this.endSize,0);
  60. ctx.lineTo(this.endSize,-this.endSize);
  61. ctx.lineTo(-this.endSize,-this.endSize);
  62. ctx.lineTo(-this.endSize,0);
  63. ctx.closePath();
  64. ctx.restore();
  65. ctx.fill();
  66. };
  67. var ArrowLine=new ArrowLine("lineDiv1");
  68. ArrowLine.draw(45,90,250,275);
  69. </script>
  70. </body>
  71. </html>


원본 참고 자료

http://stackoverflow.com/questions/16025326/html-5-canvas-complete-arrowhead

http://jsfiddle.net/m1erickson/Sg7EZ/


Posted by 시니^^