Reputation: 4192
I have a simple SVG image. There is a circle inside which I would like to rotate 90
degrees. But as you can see in JSFiddle example center of the rotation is not in the middle. What am I doing wrong?
svg {
background-color: #ddd;
}
.circle1 {
fill: none;
stroke-width: 20px;
stroke: #b5b5b5;
}
.circle2 {
fill: #aaa;
transform: rotate(-20deg);
stroke-width: 15px;
stroke: #71c7ff;
}
<svg height="600" width="600">
<circle class="circle1" cx="300" cy="300" r="200"></circle>
<circle class="circle2" cx="300" cy="300" r="200"></circle>
</svg>
Here is JSFiddle example https://jsfiddle.net/oxt681gr/1/
Upvotes: 1
Views: 1562
Reputation: 14175
By default, the origin of a transform should be 0px 0px
, but now we have wrong info on MDN:
By default, the origin of a transform is center.
It is wrong. But in the case if it would be in center of your circle you would not able to see the result of your rotation because you will rotate the circle in his center.
You can change the rotation center with CSS property transform-origin
or with SVG transform
attribute. In SVG transform
attribute we have the default also on 0px 0px
. To rotate SVG (without CSS) use transform="rotate(deg, cx, cy)"
, where deg is the degree you want to rotate and (cx, cy)
define the center of rotation.
In my solution you can change it interactive with CSS and JS:
var input = document.querySelector('input'),
circle2 = document.querySelector('.circle2'),
output = document.querySelector('span');
input.onchange = function(e)
{
var newTransformOrigin = e.target.value;
output.innerHTML = newTransformOrigin + 'px' + ' ' + newTransformOrigin + 'px';
circle2.style.transformOrigin = output.innerHTML;
};
svg {background-color:#ddd}
.circle1 {fill: none; stroke-width: 20px; stroke: #b5b5b5}
.circle2
{
fill: #aaa;
transform-origin: 0 0;
transform: rotate(-20deg);
stroke-width: 15px;
stroke: #71c7ff;
}
<p>Change transform-origin <input type="range" min="0" max="600" value="0" step="50">
<span>0px 0px</span></p>
<svg height="600" width="600">
<circle class="circle1" cx="300" cy="300" r="200"></circle>
<circle class="circle2" cx="300" cy="300" r="200"></circle>
</svg>
Please change to full page to see the example.
Upvotes: 1