experimenting with the SVG attributes viewBox and preserveAspectRatio
created with d3js v4 and ES2015
forked from enjalot's block: viewBox space coordinate transformation
| license: gpl-3.0 |
experimenting with the SVG attributes viewBox and preserveAspectRatio
created with d3js v4 and ES2015
forked from enjalot's block: viewBox space coordinate transformation
| <!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> |