Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements inside circle in svg

Tags:

html

jquery

css

svg

I am trying to find elements that comes between the co-ordinates of a circle. In the Fiddle i have a circle that animates according to mouse position i want to style/select all the small circles that come inside the area of the big circle

var s = Snap('svg')
for (var x = 10; x < 500; x = x + 30) {
  for (var y = 10; y < 500; y = y + 30) {
    var circle = s.circle(x, y, 5)
    circle.attr({
      fill: 'black' //'#8BFE03'
    })
  }
}
s.mousemove(function(e) {
  $('.circle').attr({
    cx: e.pageX,
    cy: e.pageY
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<svg width="1500" height="1500" id="svg">
  <circle class="circle" cx="0" cy='0' r='80' />
</svg>
like image 858
Akshay Avatar asked May 10 '15 09:05

Akshay


People also ask

What is cx and cy in SVG circle?

The cx and cy attributes define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle's center is set to (0,0) The r attribute defines the radius of the circle.

How can I display an image inside SVG circle in html5?

To display an image inside SVG circle, use the <circle> element and set the clipping path. The <clipPath> element is used to define a clipping path. Image in SVG is set using the <image> element.

Which tag of SVG is used to draw a circle?

<circle> The <circle> SVG element is an SVG basic shape, used to draw circles based on a center point and a radius.


1 Answers

This is a bit more accurate since compares distances. Accepted answer grabs too many small circles.

var s = Snap('svg')
    for (var x = 10; x < 500; x = x + 30) {
      for (var y = 10; y < 500; y = y + 30) {
        var circle = s.circle(x, y, 5)
        circle.attr({
          fill: 'black', //'#8BFE03'
          class: 'small'
        })
      }
    }
    s.mousemove(function(e) {
      $('.circle').attr({
        cx: e.pageX,
        cy: e.pageY
      });
      
      var circle = $(".circle");
      $(".small").each(function(){
        var dx = $(this).attr("cx") - circle.attr('cx');
        var dy = $(this).attr("cy") - circle.attr('cy');
        if((dx*dx + dy*dy) <= circle.attr('r')*circle.attr('r'))
          $(this).attr('fill','#fff');
        else
          $(this).attr('fill','#000');
      });
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<svg width="1500" height="1500" id="svg">
    <circle class="circle" cx="0" cy='0' r='80' />
</svg>
like image 85
Ruslanas Balčiūnas Avatar answered Sep 29 '22 13:09

Ruslanas Balčiūnas