Playing with rotation and transitions in d3
Really unintuitive behaviour with rotations and transitions. Or I am missing something.
by emperorz
HTML
<script src="http://d3js.org/d3.v2.min.js"></script>
JavaScript
var w = 400;
var h = 300;
var diamond1 = {
width: 40,
x: 100,
y: 100
};
var diamond2 = {
width: 40,
x: 200,
y: 100
};
var rotation1 = 15;
var rotation2 = 15;
// OK - transform only, rotate then translate
//Mostly ok, but a little wobbly
var svg = d3.select("body").append("svg").attr("width", 400).attr("height", 300);
svg.append("text").text("click each square").attr("x", w / 2).attr("y", w / 2)
svg.append("rect").attr("transform", "rotate(" + rotation1 + "," + (diamond1.x + diamond1.width / 2) + "," + (diamond1.y + diamond1.width / 2) + ")" + "translate(" + diamond1.x + ", " + diamond1.y + ")")
.attr("height", diamond1.width).attr("width", diamond1.width).attr("fill", "teal").on("mousedown", function() {
d3.select(this).transition().duration(500).attr("transform", "rotate(" + (rotation1 += 65) + "," + (diamond1.x + diamond1.width / 2) + "," + (diamond1.y + diamond1.width / 2) + ")" + "translate(" + diamond1.x + ", " + diamond1.y + ")")
});
//Here we use x,y positioning and rotate using transform
//Very wobbly.
svg.append("rect").attr("transform", "rotate(" + rotation2 + "," + (diamond2.x + diamond2.width / 2) + "," + (diamond2.y + diamond2.width / 2) + ")"
).attr("x", diamond2.x).attr("y", diamond2.y).attr("height", diamond2.width).attr("width", diamond2.width).attr("fill", "teal").on("mousedown", function() {
d3.select(this).transition().duration(500).attr("transform", "rotate(" + (rotation2 += 65) + "," + (diamond2.x + diamond2.width / 2) + "," + (diamond2.y + diamond2.width / 2) + ")"
)
});