Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Generate Path for Curly Bracket
<html>
<title>Curly Bracket</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.curlyBrace {
stroke: #000000;
stroke-width: 10px;
fill: none;
}
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
</style>
<body ontouchmove="BlockMove(event);">
<p> Click and Drag to draw a bracket </p>
<script type="text/javascript">
//returns path string d for <path d="This string">
//a curly brace between x1,y1 and x2,y2, w pixels wide
//and q factor, .5 is normal, higher q = more expressive bracket
function makeCurlyBrace(x1,y1,x2,y2,w,q)
{
//Calculate unit vector
var dx = x1-x2;
var dy = y1-y2;
var len = Math.sqrt(dx*dx + dy*dy);
dx = dx / len;
dy = dy / len;
//Calculate Control Points of path,
var qx1 = x1 + q*w*dy;
var qy1 = y1 - q*w*dx;
var qx2 = (x1 - .25*len*dx) + (1-q)*w*dy;
var qy2 = (y1 - .25*len*dy) - (1-q)*w*dx;
var tx1 = (x1 - .5*len*dx) + w*dy;
var ty1 = (y1 - .5*len*dy) - w*dx;
var qx3 = x2 + q*w*dy;
var qy3 = y2 - q*w*dx;
var qx4 = (x1 - .75*len*dx) + (1-q)*w*dy;
var qy4 = (y1 - .75*len*dy) - (1-q)*w*dx;
return ( "M " + x1 + " " + y1 +
" Q " + qx1 + " " + qy1 + " " + qx2 + " " + qy2 +
" T " + tx1 + " " + ty1 +
" M " + x2 + " " + y2 +
" Q " + qx3 + " " + qy3 + " " + qx4 + " " + qy4 +
" T " + tx1 + " " + ty1 );
}
function update()
{
var bracket = d3.select("svg").selectAll("path").attr("class","curlyBrace").data(coords);
bracket.enter().append("path").attr("class","curlyBrace");
bracket.attr("d", function(d) { return makeCurlyBrace(d.x1,d.y1,d.x2,d.y2,50,0.6); });
bracket.exit().remove();
coords.shift();
}
var width = 962;
var height = 502;
var coords = [];
var clickPos = {};
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousedown",function(){
clickPos = {"x1" : d3.mouse(this)[0], "y1": d3.mouse(this)[1]};
})
.on("mouseup", function(){
coords.push({"x1":clickPos.x1,"y1":clickPos.y1,"x2":d3.mouse(this)[0],"y2":d3.mouse(this)[1]});
update();
});
</script>
</body>
</html>

susielu commented Oct 26, 2017

Hey there, would you mind if I used this code for generating a type of bracket annotation I am making in react-annotation? I would cite this example and your username in the source code. It's been really helpful! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment