width = 200 ;
height = 200 ;
var svg = d3.select("body").append("svg").attr("id","vis")
.attr("width", width )
.attr("height", height );
var drag = d3.behavior.drag()
.on("drag", dragmove);
var anchorPoint={"x":width/2,"y":height/2};
var auxvect,ang;
svg.append("rect").attr("fill","red").attr("width",10).attr("height",30).call(drag);
//anchor point circle reference
svg.append("circle").attr("cx",width/2).attr("cy",height/2).attr("r","5");
svg.append("text").attr("transform","translate(20,20)").text("Drag the red rectangle").attr("fill","white");
function dragmove(d) {
//get mouse coordinates
var x = d3.event.x;
var y = d3.event.y;
//get the perpendicular from the vector between the mouse coordinates and the anchorPoint
auxvect ={"x": x-anchorPoint.x,"y":-(y-anchorPoint.y)};
//get the angle between vector (0,1) and auxvect.
//http://stackoverflow.com/questions/12903547/fastest-way-to-find-the-angle-between-two-points
ang= Math.acos( auxvect.x / Math.sqrt(auxvect.x*auxvect.x + auxvect.y*auxvect.y) );
ang = ang * 180 / Math.PI;//in degrees
//transform the rect
if(y<anchorPoint.y){
d3.select(this).attr("transform", "translate(" + x + "," + y + ")rotate("+(-ang)+")");
}else{
d3.select(this).attr("transform", "translate(" + x + "," + y + ")rotate("+(ang)+")");
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.