SVG getAbsoluteCTM getCTM
negates the effect of viewBox attribute on the return value from element.getCTM
by Ibrahim Tanyalcin
HTML
<div id="container"></div>
CSS
svg {
width:100%;
height:100%;
}
#container {
width:400px;
height:300px;
}
JavaScript
!function(prt){
prt._getAbsoluteCTM = function(){
var owner = this.ownerSVGElement || this,
height = owner.height.baseVal.value,
width = owner.width.baseVal.value,
viewBoxRect = owner.viewBox.baseVal,
vHeight = viewBoxRect.height,
vWidth = viewBoxRect.width;
if(!vWidth || !vHeight){
return this.getCTM();
}
var sH = height/vHeight,
sW = width/vWidth,
matrix = owner.createSVGMatrix();
matrix.a = sW;
matrix.d = sH
var realCTM = this.getCTM().multiply(matrix.inverse());
realCTM.e = realCTM.e/sW + viewBoxRect.x;
realCTM.f = realCTM.f/sH + viewBoxRect.y;
return realCTM;
}
}(SVGGraphicsElement.prototype);
var svg = d3.select("#container").append("svg")
.attr("preserveAspectRatio","none")
.attr("viewBox","-500 -500 2000 2000");
var circle = svg.append("circle").attr("r",20).attr("cx",Math.random()*1000)
.attr("cy",Math.random()*1000).attr("fill","Gray").attr("transform","translate(50,50)");
var rect = svg.append("rect").attr("x",200).attr("y",200).attr("width",200)
.attr("height",200).attr("fill","Gray").attr("transform","translate(50,50) rotate(10)");