Creating a scale transform using SVG DOM

407 views Asked by At

I try the code above and get :

Uncaught TypeError: Cannot read property 'setScale' of undefined

I understand that the problem rise from attributing type scale to my transform. Any idea ?

    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <svg id= "test" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <script><![CDATA[

    var test=document.getElementById("test");
    var svgns = test.namespaceURI;
    var doc = document;

    onload=function init(){

    var t=doc.createElementNS(svgns,"rect");
    t.setAttribute("x",0);
    t.setAttribute("y",0);
    t.setAttribute("width",100);
    t.setAttribute("height",200);
    alert(t.width.baseVal.value);

    var Redimmensionnement=doc.createElementNS(svgns,"transform"); 
    Redimmensionnement.setAttribute("type",3).setScale(.75,1.2);
    t.setAttribute("transform",Redimmensionnement);
    alert(t.width.baseVal.value);

    }
    ]]>
    </script>
    </svg>
1

There are 1 answers

1
Robert Longson On

I assume what you really want is something like this. Note that you create a transform object using createSVGTransform and not createElementNS.

    var test=document.getElementById("test");
    var svgns = test.namespaceURI;
    var doc = document;

    onload=function init(){

    var t=doc.createElementNS(svgns,"rect");
    t.setAttribute("x",0);
    t.setAttribute("y",0);
    t.setAttribute("width",100);
    t.setAttribute("height",200);

    var Redimmensionnement=test.createSVGTransform(); 
    Redimmensionnement.setScale(.75,1.2);
    t.transform.baseVal.initialize(Redimmensionnement);
    alert(t.getAttribute("transform"));
}
 
html, body, svg {
  width: 100%;
  height: 100%;
}
<svg id="test" onload="init()"></svg>