Javascript required
Skip to content Skip to sidebar Skip to footer

Javascript Draw Concentric Circles Canvas

Recently one of our customers wanted to accept a webpage with an illustration including concentric circles / rings with clickable text on the arcs. When the user clicks on the texts nosotros should display related information from SharePoint lists, but information technology is irrelevant to the primary topic of this post. Our first idea was to create a static paradigm map, only the client informed us, that the texts and the arrangement might change several times, and so I preferred some kind of dynamic solution and decided to utilise HTML5 and JavaScript.

In this post I would like to introduce the results of my piece of work and share the code with the community.

First I created a few JavaScript "classes" describing entities similar a circumvolve / band (with attributes similar eye, inner and outer radius) and arc (with attributes like kickoff and terminate angle, text and text alignment). Then I defined helper functions that enable creation of rings or appending arcs adjacent to each other. Finally I wrote the necessary methods to draw the arcs, to write text along the arcs (supporting multiline text, various alignments like align to left, correct, centre or justify, and support to write text acme-downwardly at the upper part of the circle and lesser-up at the lower function), and to detect if the mouse is over an arc (and if it is, highlight the arc), and to react on mouse click.

Note: Multiline text support in this version is limited to explicit line breaks ('\n' in text), no automatic word wrapping.

The algorithms in the solution require a solid understanding of trigonometry. Fortunately, I constitute several resources on the spider web (encounter the source lawmaking at the lesser for related URLs) that helped me in the first steps.

The screenshot below illustrates a sample including a few rings and arcs for each band. Note the diverse text directions (at the superlative and bottom parts of the circles, like the directions of "Test 2" versus direction of "Test 3") and text alignments.

Note: In this implementation the circles and arcs are hardcoded, but you are free to get the data to initialization from a background system, like SharePoint lists or so.

image

When a mouse hovers over an arc, the arc is highlighted with an other background color.

image

Annotation: Using a significantly unlike background color for highlighting does not work well (you tin can try it for example using cerise instead of gray, like illustrated below), every bit afterward the mouse moves out from the area and the original background color is applied over again, the borders of the arcs remain "muddied".

image

Finally, the arc reacts on mouse click with an alert including the text of the arc, nonetheless yous can extend the solution with more advanced interaction, like calling Rest interfaces to display the response dynamically.

image

Beneath I publish the whole source lawmaking of this sample solution.

  1. <! DOCTYPE HTML >
  2. < html >
  3. < head >
  4. < style >
  5. body
  6.         {
  7. margin: 0px;
  8. padding: 0px;
  9.         }
  10. </ style >
  11. </ caput >
  12. < body >
  13. < canvass id ="myCanvas" width ="800" summit ="800"></ sail >
  14. < script >
  15. // http://www.html5canvastutorials.com/tutorials/html5-sheet-arcs/
  16. // http://world wide web.html5canvastutorials.com/labs/html5-canvas-text-along-arc-path/
  17. var canvas = certificate.getElementById('myCanvas');
  18.         canvas.addEventListener('mousemove', track_mouse, imitation);
  19.         canvas.addEventListener('click', click_mouse, false);
  20.         TextAlignment = {
  21.             Left : 0,
  22.             Center : 1,
  23.             Right : 2,
  24.             Justify : 3
  25.         }
  26. function point (x, y) {
  27. this.x = 10;
  28. this.y = y;
  29.         }
  30. function band (center, minRadius, maxRadius) {
  31. this.middle = center;
  32. this.minRadius = minRadius;
  33. this.maxRadius = maxRadius;
  34.         }
  35. function arc (ring, startAngle, endAngle, text, alignment) {
  36. this.ring = band;
  37. this.startAngle = startAngle;
  38. this.endAngle = endAngle;
  39. this.text = text;
  40. this.alignment = (alignment != undefined) ? alignment : TextAlignment.Center;
  41. this.createArcAfter = role (angle, text) {
  42. render new arc(this.band, this.endAngle, this.endAngle + bending, text);
  43.             };
  44. this.createArcAfterUpTo = function (upToArc, text) {
  45. return new arc(this.ring, this.endAngle, upToArc.startAngle, text);
  46.             };
  47. this.isInside = function (pos) {
  48. // http://stackoverflow.com/questions/6270785/how-to-make up one's mind-whether-a-point-ten-y-is-contained-inside-an-arc-department-of-a-c
  49. // Angle = arctan(y/10); Radius = sqrt(x * x + y * y);
  50. var upshot = false;
  51. var radius = Trig.distanceBetween2Points(pos, this.ring.heart);
  52. // we summate atan simply if the radius is OK
  53. if ((radius >= this.ring.minRadius) && (radius <= this.ring.maxRadius)) {
  54. var angle = Trig.angleBetween2Points(this.ring.center, pos);
  55. var a = (angle < 0) ? bending + 2 * Math.PI : angle;
  56. var sa = this.startAngle;
  57. var ea = this.endAngle;
  58. if (ea > 2 * Math.PI) {
  59.                         sa -= 2 * Math.PI;
  60.                         ea -= two * Math.PI;
  61.                     }
  62. if (sa > ea) {
  63.                         sa -= 2 * Math.PI;
  64.                     }
  65. if ((a >= sa) && (a <= ea)) {
  66.                         outcome = truthful;
  67.                     }
  68.                 }
  69. return effect;
  70.             };
  71. this.higlightIfInside = function (pos) {
  72. if (this.isInside(pos)) {
  73.                     arc.isHighlighted = this;
  74.                     drawArc(this, true);
  75.                 }
  76.             };
  77. this.doTask = role (pos) {
  78. if (this.isInside(pos)) {
  79.                     alert(this.text);
  80.                 }
  81.             };
  82. if (arc.arcs == undefined) {
  83.                 arc.arcs = new Array();
  84.             }
  85.             arc.arcs.button(this);
  86.         }
  87.         arc.lastHighlighted = null;
  88.         arc.isHighlighted = null;
  89.         arc.drawAll = function () {
  90.             arc.arcs.forEach(function (a) {
  91.                 drawArc(a);
  92.             });
  93.         }
  94.         arc.checkMousePos = function (pos) {
  95.             arc.lastHighlighted = arc.isHighlighted;
  96.             arc.isHighlighted = naught;
  97.             arc.arcs.forEach(function (a) {
  98.                 a.higlightIfInside(pos);
  99.             });
  100. if ((arc.lastHighlighted != null) && (arc.isHighlighted != arc.lastHighlighted)) {
  101.                 drawArc(arc.lastHighlighted);
  102.             }
  103. // set cursor co-ordinate to the highlight status
  104.             canvas.style.cursor = (arc.isHighlighted != null) ? 'arrow' : 'default';
  105.         }
  106.         arc.doTasks = function (pos) {
  107.             arc.arcs.forEach(function (a) {
  108.                 a.doTask(pos);
  109.             });
  110.         }
  111. // http://www.tricedesigns.com/2012/01/04/sketching-with-html5-sail-and-brush-images/
  112. var Trig = {
  113.             distanceBetween2Points: function (point1, point2) {
  114. var dx = point2.x – point1.x;
  115. var dy = point2.y – point1.y;
  116. return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, ii));
  117.             },
  118.             angleBetween2Points: role (point1, point2) {
  119. var dx = point2.ten – point1.10;
  120. var dy = point2.y – point1.y;
  121. render Math.atan2(dy, dx);
  122.             },
  123.             angleDiff: function (startAngle, endAngle) {
  124. var angleDiff = (startAngle – endAngle);
  125.                 angleDiff += (angleDiff > Math.PI) ? -2 * Math.PI : (angleDiff < -Math.PI) ? 2 * Math.PI : 0
  126. render angleDiff;
  127.             }
  128.         }
  129. var centre = new indicate(canvas.width / ii, canvas.height / two);
  130. var r1 = new ring(middle, 100, 150);
  131. var arc1 = new arc(r1, 1.4 * Math.PI, one.9 * Math.PI, "It's a test");
  132. var arc1_2 = arc1.createArcAfter(0.6 * Math.PI, "This is a\nmultiline text");
  133. var arc1_3 = arc1_2.createArcAfterUpTo(arc1, "Inner examination");
  134. var r2 = new ring(center, 160, 210);
  135. var arc2 = new arc(r2, 0 * Math.PI, 0.six * Math.PI, "Exam messgae");
  136. var arc2_1 = arc2.createArcAfter(0.3 * Math.PI, "Test 2");
  137. var arc2_2 = arc2_1.createArcAfter(0.3 * Math.PI, "Examination three");
  138. var r3 = new ring(center, 220, 270);
  139. var arc3 = new arc(r3, 0 * Math.PI, 1 * Math.PI, "Left aligned text", TextAlignment.Left);
  140. var arc3_1 = new arc(r3, i * Math.PI, i.5 * Math.PI, "Right aligned text", TextAlignment.Right);
  141. var arc3_2 = new arc(r3, 1.five * Math.PI, 2 * Math.PI, "Justified text", TextAlignment.Justify);
  142. var context = sail.getContext('2d');
  143.         arc.drawAll();
  144. function drawArc(arc, isHighlighted) {
  145. var gapsAtEdgeAngle = Math.PI / 400;
  146. var isCounterClockwise = false;
  147. var startAngle = arc.startAngle + gapsAtEdgeAngle;
  148. var endAngle = arc.endAngle – gapsAtEdgeAngle;
  149.             context.beginPath();
  150. var radAvg = (arc.band.maxRadius + arc.ring.minRadius) / 2;
  151.             context.arc(arc.ring.heart.10, arc.ring.center.y, radAvg, startAngle, endAngle, isCounterClockwise);
  152.             context.lineWidth = arc.ring.maxRadius – arc.ring.minRadius;
  153. // line color
  154.             context.strokeStyle = isHighlighted ? 'greyness' : 'lightgrey';
  155.             context.stroke();
  156.             drawTextAlongArc(arc.text, center, radAvg, startAngle, endAngle, arc.alignment);
  157.         }
  158. part drawTextAlongArc(text, center, radius, startAngle, endAngle, alignment) {
  159. var fontSize = 12;
  160. var lineSpacing = 4;
  161. var lines = text.split('\n');
  162. var lineCount = lines.length;
  163.             radius = radius + (lineCount – 1) / 2 * (fontSize + lineSpacing)
  164.             lines.forEach(office (line) {
  165.                 drawLineAlongArc(context, line, eye, radius, startAngle, endAngle, fontSize, alignment);
  166.                 radius -= (fontSize + lineSpacing);
  167.             });
  168.         }
  169. function drawLineAlongArc(context, str, center, radius, startAngle, endAngle, fontSize, alignment) {
  170. var len = str.length, s;
  171.             context.relieve();
  172.             context.font = fontSize + 'pt Calibri';
  173.             context.textAlign = 'eye';
  174.             context.fillStyle = 'black';
  175. // check if the arc is more at the top or at the lesser part of the ring
  176. var upperPart = ((startAngle + endAngle) / 2) > Math.PI;
  177. // reverse the aligment management if the arc is at the lesser
  178. // Center and Justify is neutral in this sence
  179. if (!upperPart) {
  180. if (alignment == TextAlignment.Left) {
  181.                     alignment = TextAlignment.Right;
  182.                 }
  183. else if (alignment == TextAlignment.Right) {
  184.                     alignment = TextAlignment.Left;
  185.                 }
  186.             }
  187. //var metrics = context.measureText(str);
  188. var metrics = context.measureText(str.supplant(/./gi, 'Due west'));
  189. var textAngle = metrics.width / (radius – fontSize / two);
  190. var gapsAtEdgeAngle = Math.PI / 80;
  191. if (alignment == TextAlignment.Left) {
  192.                 startAngle += gapsAtEdgeAngle;
  193.                 endAngle = startAngle + textAngle;
  194.             }
  195. else if (alignment == TextAlignment.Center) {
  196. var advertisement = (Trig.angleDiff(endAngle, startAngle) – textAngle) / 2;
  197.                 startAngle += advertisement;
  198.                 endAngle -= advertizement;
  199.             }
  200. else if (alignment == TextAlignment.Right) {
  201.                 endAngle -= gapsAtEdgeAngle;
  202.                 startAngle = endAngle – textAngle;
  203.             }
  204. else if (alignment == TextAlignment.Justify) {
  205.                 startAngle += gapsAtEdgeAngle;
  206.                 endAngle -= gapsAtEdgeAngle;
  207.             }
  208. else {
  209. // alignmet not supported
  210. // show some kind of alarm
  211. // or fallback to default?
  212.             }
  213. // summate text height and arrange radius according to font size
  214. if (upperPart) {
  215. // if it is in the upper part, nosotros have to change the orientation too -> multiply past -1
  216.                 radius = -one * (radius – fontSize / 2);
  217.             }
  218. else {
  219.                 radius += fontSize / 2; //*
  220.             }
  221.             context.translate(center.x, center.y);
  222. var angleStep = Trig.angleDiff(endAngle, startAngle) / len;
  223. if (upperPart) {
  224.                 angleStep *= -1;
  225.                 context.rotate(startAngle + Math.PI / 2);
  226.             }
  227. else {
  228.                 context.rotate(endAngle – Math.PI / 2);
  229.             }
  230.             context.rotate(angleStep / 2);
  231. for (var n = 0; n < len; n++) {
  232.                 context.rotate(-angleStep);
  233.                 context.save();
  234.                 context.interpret(0, radius);
  235.                 s = str[northward];
  236.                 context.fillText(southward, 0, 0);
  237.                 context.restore();
  238.             }
  239.             context.restore();
  240.         }
  241. function track_mouse(e) {
  242. var target = eastward.currentTarget;
  243. var mousePos = getMousePos(target, east);
  244.             arc.checkMousePos(mousePos);
  245.         }
  246. office click_mouse(e) {
  247. var target = e.currentTarget;
  248. var mousePos = getMousePos(target, east);
  249.             arc.doTasks(mousePos);
  250.         }
  251. function getMousePos(canvas, evt) {
  252. var rect = canvas.getBoundingClientRect();
  253. return {
  254.                 x: evt.clientX – rect.left,
  255.                 y: evt.clientY – rect.top
  256.             };
  257.         }
  258. </ script >
  259. </ body >
  260. </ html >

Any comments and ideas to further enhancements are welcome.

beamontcortild.blogspot.com

Source: https://pholpar.wordpress.com/2014/03/13/creating-a-set-of-concentric-circles-with-texts-using-html5-and-javascript/