Search code examples
javascriptsvgjsfiddle

How to add number to circle


I have used jsFiddle to create a number of circles with predefined locations. How can I add numbers on theses circles, so that each circle has a number ?

jsfiddle code

function draw_circle(center_x, center_y){
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var centerX = center_x;
    var centerY = center_y;
    var radius = 30
    ;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'lightblue';
    context.fill();
    context.lineWidth =3;
    context.strokeStyle = '#003300';
    context.stroke();
  }

Solution

  • I made a simplified version of your sample showing how to number the circles

    The textnode is appended right after the circle. The opacity of the circle is set to 0.5, otherwise the text is covered by the circle.

    <!DOCTYPE html>
    <head>
        <meta charset="UTF-8">
        <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
        <style>
         svg .circle {
             stroke: yellow;
             opacity: 0.5;
             stroke-width: 2;
         }
         </style> 
    </head>
    <body>
    <script type="text/javascript">
    $(document).ready(function() {
        var width = 900, height = 650;
        var radius = 30; 
        var numCircles = 10;
        var circles=[[133,396],[234,511.0000305175781],[369,116],[348,388],[231,278],[351,232],[520,228],[116,199],[522,425],[229,120]];
        var svg = d3.select("body").append("svg").attr("width", width).attr("height", height).attr("id", 'svg');
        var g_circles = svg.append("g").attr("class", "circles");
        $.each(circles, function(i, d) {
            g_circles.append("circle").attr("class", "circle").attr("id", "circle" + i).attr("r", radius).attr("cx", d[0]).attr("cy", d[1]);
            g_circles.append("text").attr("x", d[0]-5).attr("y", d[1]+5).text(i);
        });
    });
          </script>
    </body></html>