asker22
asker22

Reputation: 205

Rotation of elements added dynamically to SVG

I have a HTML page with one <svg> element inside it. When it is loaded rectangles are added to it dynamically. Each <rect> is registered to an onclick event where I'm rotating it.

My problem is that I desire the <rect>s to rotate on their center point, and not on left upper corner of the SVG element they sit inside. How can I acheive this?

My HTML code:

<!DOCTYPE html>
<html>
<head>
<title>HTML5 Demo</title>   
<script lang="javascript" src="HTML5-Script.js"></script>
</head>
<body>
<svg onload="DrawRects()" id="SVG" width="800" height="600"></svg>
</body>
</html>

My script code:

function DrawRects() {
    setInterval(function () { CreateRect(); }, 2000);
}

function CreateRect() {
    var svg = document.getElementById("SVG");
    var svgns = "http://www.w3.org/2000/svg";
    var shape = document.createElementNS(svgns, "rect");
    shape.setAttributeNS(null, "x", Math.floor((Math.random() * 200) + 10));
    shape.setAttributeNS(null, "y", Math.floor((Math.random() * 200) + 10));
    shape.setAttributeNS(null, "width", Math.floor((Math.random() * 400) + 10));
    shape.setAttributeNS(null, "height", Math.floor((Math.random() * 400) + 10));

    var red = Math.floor((Math.random() * 256) + 1);
    var green = Math.floor((Math.random() * 256) + 1);
    var blue = Math.floor((Math.random() * 256) + 1);
    var color = 'rgb(' + red + ',' + green + ',' + blue + ')';

    shape.setAttributeNS(null, "fill", color);
    shape.id = "R" + Math.floor((Math.random() * 50));
    shape.setAttributeNS(null, "onclick", "RectClick(this)");  
    document.getElementById('SVG').appendChild(shape);
}

function RectClick(shape) {
    Rotate(shape,0);    
}

function Rotate(shape,angle) {

    setInterval(function () {
        angle++;
        shape.style.webkitTransform = "rotate(" + angle + "deg)";
       }, 60);
}

Upvotes: 0

Views: 1121

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101938

You can use transform-origin to set the origin of the transforms provided by the CSS transform property.

https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin

Upvotes: 1

Related Questions