I want to add a rectangle in my d3.js graph highlighting a specific data region. The problem is I don't want to specify a starting point and then a height and length.
Rather I would like to specify two points positioned diametral – on the upper left and lower right corner of the rectangle. The highlight area rectangle needs to go from my lowest X value to the highest X value in my dataset and from a specific lower y bound to a specific higher y bound.
Update: Just use a plain svg
rect
object.The trick is to build the rectangle yourself out of lines rather than to use the rect element provided by d3.js.
I use this function:
Usage:
Complete example:
If you are just passing the
x
andy
values of the two points, why not using arect
element itself? It's way shorter and easier than drawing a path as in your answer:Here is your demo:
The only difference between this and your code is that this doesn't check for negative width/height values (but it doesn't matter, because you said that you're passing the top left as the first pair and the bottom right as the second). Besides that, it's worth mentioning that
rect
has nothing to do with D3, it's an SVG element and its specifications are provided by W3C.