Pradyumna Pradyumna - 1 month ago 9
Javascript Question

Snap.svg return object says "Object has no circle method"

I'm trying to wrap an existing svg element with Snap. When I try to create a circle, I get an error:

var e = document.getElementById("svgId");


var paper = Snap(e);

var button1 = paper.circle(20,20,50);


The above code generates this error:

Uncaught TypeError: Object [object Object] has no method 'circle'

I am very new to js and even more so to svg. Any help regarding this matter is very much appreciated.

The following demo produces the same error:

<!DOCTYPE html>`
<html>
<head lang="en">
<script type="text/javascript" src="snap.svg-min.js"></script>
<script type="text/javascript">
function init(){
var e = document.createElement("svg");
e.id = "demo";
var paper = Snap(e);
console.log(paper);
var button1 = paper.circle(20,20,50);
button1.attr({
fill:"#bbbb55",
stroke:"000",
strokeWidth: 3
});
}
</script>
</head>
<body onload="init()">
</body>
</html>

Ian Ian
Answer

I'm going to include 3 different examples on the same page, as its sometimes useful to see and compare...

1st example circle, is from a dynamically created svg element similar to your example (note, you needed append the svg element to the body in your example as well, and probably use createElementNS).

2nd example circle, is from svg markup in the body.

3rd example circle, is to let Snap create the element itself (normally the way, or to use an svg element, like Snap("#container")).

jsfiddle here

    var e = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    e.setAttribute('style', 'border: 1px solid black');
    e.setAttribute('width', '600');
    e.setAttribute('height', '250');
    e.id="svg1";
    document.body.appendChild( e );

    var paper1 = Snap( "#svg1" ); //use element created above
    var button1 = paper1.circle(100,100,100);
    button1.attr({
             fill:"blue",
             stroke:"green",
             strokeWidth: 3
            });

    var paper2 = Snap( "#svg2" ); //use element from markup below
    var button2 = paper2.circle(100,100,100);
    button2.attr({
             fill:"red",
             stroke:"yellow",
             strokeWidth: 3
            });

    var paper3 = Snap(200,200); //let Snap create element
    var button3 = paper3.circle(100,100,100);
    button3.attr({
             fill:"purple",
             stroke:"silver",
             strokeWidth: 3
            });

<body onload="init()">

....

<svg id="svg2" width="200" height="200">
    <circle r="20" cx="20" cy="20"/>
</svg>

</body>
</html>