score:0

Accepted answer

You need to provide a different value for the style("fill", ...) property on each circle. This will cause each new circle to have a different color but will not change the color of existing circles (that is somewhat more complex).

If you want a random selection from a prepared list of colors, you should create an array of colors (by name or hex code) and a function to return a random color. Each time you draw a circle, call the function and it will select and return a color from the array.

Something like so:

var colors = ["red", "green", "blue", "yellow", "orange", "purple", "gray"];

function getColor() {
  return colors[Math.round(Math.random() * colors.length)];
}

(function() {
  var svg = d3.select('svg');

  function drawCircle(x, y, size) {
    console.log('Drawing circle at', x, y, size);
    svg.append("circle")
      .style("fill", getColor())
      .attr("cx", x)
      .attr("cy", y)
      .attr("r", size);
  }

  svg.on('click', function() {
    var coords = d3.mouse(this);
    console.log(coords);
    drawCircle(coords[0], coords[1], 5);
  });


})();
.plot {

  background-color: #000;

  width: 500px;

  height: 500px;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg class="plot">
</svg>

To use the colors in order, you would just keep a counter like:

var colors = ["red", "green", "blue", "yellow", "orange", "purple", "gray"];
var colorState = 0;

function getColor() {
  var color = colors[colorState];
  colorState = (colorState + 1) % colors.length; // keep it from going OOB
  return color;
}

score:0

Use this:

svg.style("fill",'#'+Math.floor(Math.random()*16777215).toString(16));

as the function :

'#'+Math.floor(Math.random()*16777215).toString(16);

would return an Hex number from 000000 to FFFFFF.

Ps: 16777215 is FFFFFF in decimale.

Hope this helped you.

score:0

With the help of this answer for the random color, here is what you could do:

(function() {
    var svg = d3.select('svg');

    function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    function drawCircle(x, y, size) {
        console.log('Drawing circle at', x, y, size);
        svg.append("circle")
            .style('fill',getRandomColor())
            .attr("cx", x)
            .attr("cy", y)
            .attr("r", size);
    }

    svg.on('click', function() {
        var coords = d3.mouse(this);
        console.log(coords);
        drawCircle(coords[0], coords[1], 5);
    });


})();

I updated you jsFiddle: https://jsfiddle.net/2yczn6q3/19/


Related Query

More Query from same tag