So,I have a SVG rect that I can move to the mouse position,with mouseonmove.
It works fine,but when I come to rotate it,the movement is good,but It have a strange offset based on the rotated angle.I guess something is wrong at the cos/sin code,but I can't get what is wrong.
var container = document.getElementById("container");
var rect = document.getElementById("rect");
var grados = document.getElementById("grados");
var group = document.getElementById("group");
grados.addEventListener("change",rotate);
container.addEventListener("mousemove", move);
var angle = 0;
var radian = angle * Math.PI / 180;
var cos = Math.cos(radian);
var sin = Math.sin(radian);
function move(e){
var x = ((e.offsetX * cos) + (e.offsetY * sin));
var y = ((-e.offsetX * sin) + (e.offsetY * cos));
rect.setAttribute('x',x);
rect.setAttribute('y',y);
}
function rotate(e){
console.log(e);
group.style.transform='rotate('+e.target.value+'deg)';
angle = e.target.value;
radian = angle * Math.PI / 180;
cos = Math.cos(radian);
sin = Math.sin(radian);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ROTATE<input id="grados" type="number" value="1">
<svg id="container"style="width: 400px;height:400px;border:1px solid black;">
<svg>
<g id="group"style="transform:rotate(0deg);transform-origin:50% 50%;">
<rect id="rect" x="20" y="5" width="50px" height="50px" style="fill:red;stroke-width:3;stroke:blue"></rect>
</g>
</svg>
</svg>
Thanks
Well, after a few days of working, I got it. Seems like the way I was doing it was right, but it causes strange behavior with the transform-origin: '50% 50%'
property.I just removed it and everything worked. (with a few bugs, but the problem in the question is resolved).
So I just leave the answer here for the future.