Skip to content

Instantly share code, notes, and snippets.

@curran
Last active January 25, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/8c7c6467a17bd9f4f67e5be84a020a77 to your computer and use it in GitHub Desktop.
Save curran/8c7c6467a17bd9f4f67e5be84a020a77 to your computer and use it in GitHub Desktop.
Fullsize.js Prototype
license: mit
// A utility for creating "full size" graphics programs with D3.js.
// Useful for full-screen graphics, or graphics indended for use inside iFrames.
function fullsize(render){
// Append a div to the body,
// make it fill the display using CSS,
// store a reference to the DOM node for later use.
var div = d3.select("body")
.append("div")
.style("position", "fixed")
.style("left", "0px")
.style("right", "0px")
.style("top", "0px")
.style("bottom", "0px")
.node();
// Append an SVG as a child of the container DOM node.
var svg = d3.select(div)
.append("svg");
// This function updates the size of the SVG
// and invokes the render() function.
function redraw(){
// Extract the width and height that was computed by CSS.
var width = div.clientWidth;
var height = div.clientHeight;
// Use the extracted size to set the size of an SVG element.
svg
.attr("width", width)
.attr("height", height);
// Invoke the render function passed into fullsize().
render(svg, width, height);
}
// Draw for the first time to initialize.
redraw();
// Redraw based on the new size whenever the browser window is resized.
window.addEventListener("resize", redraw);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fullsize.js Prototype</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script src="fullsize.js"></script>
<script>
// Invoke the fullsize.js library.
// This adds an SVG element to the page,
fullsize(render);
// This render function will be invoked on page load,
// and every time the browser window resizes,
// passing the updated width and height.
function render(svg, width, height){
// Draw an X to show that the size is correct.
var data = [
{x1: 0, y1: 0, x2: width, y2: height},
{x1: 0, y1: height, x2: width, y2: 0}
];
var lines = svg.selectAll("line").data(data);
lines.enter()
.append("line")
.style("stroke-width", 50)
.style("stroke-opacity", 0.4)
.style("stroke", "black")
.merge(lines)
.attr("x1", function (d) { return d.x1; })
.attr("y1", function (d) { return d.y1; })
.attr("x2", function (d) { return d.x2; })
.attr("y2", function (d) { return d.y2; });
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment