Created
October 10, 2011 21:11
-
-
Save enjalot/1276555 to your computer and use it in GitHub Desktop.
viewBox space coordinate transformation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Aspect Ratio</title> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.3.0"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?2.3.0"></script> | |
</style> | |
</head> | |
<body> | |
<div id="chart"></div> | |
<script type="text/javascript"> | |
var make_point = function(element, xy) | |
{ | |
console.log(element); | |
//var matrix = element.getCTM(); | |
//var matrix = element.getScreenCTM(); | |
var p = element.nearestViewportElement.createSVGPoint(); | |
var matrix = element.getTransformToElement(element.nearestViewportElement); | |
p.x = xy[0]; | |
p.y = xy[1]; | |
var sp = p.matrixTransform(matrix); | |
return sp; | |
} | |
var box_example = function(w, h) | |
{ | |
//setup svg canvas | |
var svg = d3.select("#chart") | |
.append("svg:svg") | |
//.attr("width", "1000") | |
//.attr("height", "700") | |
//Aspect ratio intentionally skewed | |
.attr("width", w) | |
.attr("height", h) | |
.attr("viewBox", "0 0 400 400") | |
.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") | |
var mybox = svg.append("svg:rect") | |
.attr("width", 200) | |
.attr("height", 200) | |
.attr("transform", "translate(100,100)") | |
.attr("fill", "#00ff00") | |
.attr("fill-opacity", .8) | |
.attr("stroke", "#000") | |
.attr("stroke-width", 5) | |
.attr("stroke-opacity", .6) | |
var boxnode = mybox.node(); | |
var bbox = boxnode.getBBox(); | |
console.log(bbox); | |
var topleft = make_point(boxnode, [bbox.x, bbox.y]); | |
var circle = svg.append("svg:circle") | |
.attr("cx", topleft.x) | |
.attr("cy", topleft.y) | |
.attr("r", 20) | |
.attr("stroke", "none") | |
.attr("fill", "#ff0000") | |
.attr("fill-opacity", .6) | |
} | |
//1 to 1 between screen pixels and viewBox | |
box_example(400, 400); | |
//skewed | |
box_example(500, 320); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment