Skip to content

Instantly share code, notes, and snippets.

@micahstubbs
Last active July 25, 2016 19:31
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 micahstubbs/d7f91cec084294c4e2be2b6a60db041b to your computer and use it in GitHub Desktop.
Save micahstubbs/d7f91cec084294c4e2be2b6a60db041b to your computer and use it in GitHub Desktop.
viewBox space coordinate transformation
license: gpl-3.0
<!DOCTYPE html>
<html>
<head>
<title>viewBox space coordinate transformation</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script>
<script src='https://npmcdn.com/babel-core@5.8.34/browser.min.js'></script>
</head>
<body>
<script lang='babel' type='text/babel'>
const boxExample = (w, h) => {
//
// setup a parent svg
//
const svg = d3.select('body')
.append('svg:svg')
// .attr('width', '1000')
// .attr('height', '700')
.attr('width', w)
.attr('height', h)
.attr('viewBox', '0 0 100 100')
.attr('preserveAspectRatio', 'xMinYMin meet')
.attr('id', 'charts');
svg.append('svg:rect')
.attr('width', '100%')
.attr('height', '100%')
.attr('stroke', '#000')
.attr('stroke-width', 1)
.attr('fill', 'none');
//
// setup the square
//
// 100 is the value we use by convention
// for the width and height of the viewBox
// initialize the square side length as half of that value
const sideLength = 100 / 2;
const halfSideLength = sideLength / 2;
const mybox = svg.append('svg:rect')
.attr('width', sideLength)
.attr('height', sideLength)
.attr('transform', `translate(${halfSideLength}, ${halfSideLength})`)
.attr('fill', '#00ff00')
.attr('fill-opacity', 0.8)
.attr('stroke', '#000')
.attr('stroke-width', 5)
.attr('stroke-opacity', 0.6);
const boxnode = mybox.node();
const bbox = boxnode.getBBox();
console.log('bbox', bbox);
};
//
// draw some boxes with squares inside
//
// 1 to 1 relationship between screen pixels and viewBox
boxExample(100, 100);
// skewed shape specified, but fixed aspect ratio,
// since we set preserveAspectRatio `xMinYMin`
boxExample(333, 200);
// larger now, a 3 to 1 relationship between screen pixels and viewBox
boxExample(300, 300)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment