user3663071
user3663071

Reputation: 265

How to rotate individual SVG elements with jQuery/Javascript?

I have a SVG with repeated rectangle shapes. On scroll, each rectangle should individually rotate. The problem I'm having is that the entire SVG block rotates, and not individually.

Is it possible to target the script to treat each rectangle as an individual element to rotate?

Here is my: JSFiddle

Here is a rotation solution I found somewhere, but it affects the entire SVG:

$(function() {

  var sdegree = 0;

  $(window).scroll(function() {

  sdegree ++ ;
  sdegree = sdegree + 2 ;
  var srotate = "rotate(" + sdegree + "deg)";
  $("rect").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
  });

});

Upvotes: 1

Views: 5441

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

The rectangles are all rotating around the origin of the page (the top left). If you want them to rotate about their own centres, then you will need to include a transform-origin in your CSS rule.

$(function() {

  var sdegree = 0;

  $(window).scroll(function() {
    sdegree ++ ;
    sdegree = sdegree + 2 ;
    var srotate = "rotate(" + sdegree + "deg)";
    $("rect").css({
      "-webkit-transform" : srotate,
      "transform" : srotate,
      "-webkit-transform-origin" : "50% 50%",
      "transform-origin" : "50% 50%"
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg width="400" height="1900">
  <rect x="100" y="100" width="200" height="200" fill="red"/>
  <rect x="100" y="400" width="200" height="200" fill="orange"/>
  <rect x="100" y="700" width="200" height="200" fill="yellow"/>
  <rect x="100" y="1000" width="200" height="200" fill="green"/>
  <rect x="100" y="1300" width="200" height="200" fill="blue"/>
  <rect x="100" y="1600" width="200" height="200" fill="violet"/>
</svg>

Upvotes: 4

Related Questions