Asked By: Anonymous
Below you see a small test element. It creates a SVG and whenever you click the SVG it should add a circle. Inspecting the element shows that the circles are indeed added (I know the position isn’t exactly correct), but they are not shown.
This is svg-test.html
<link rel="import" href="../polymer/polymer.html">
<dom-module name="svg-test">
<link rel="import" type="css" href="svg-test.css">
<template>
<svg id="test" width$="{{width}}" height$="{{height}}" xmlns="http://www.w3.org/2000/svg"></svg>
</template>
<script>
Polymer({
is: 'svg-test',
properties: {
width: {
type: String,
value: "200"
},
height: {
type: String,
value: "200"
}
},
listeners: {
'test.tap': 'addCircle'
},
addCircle: function(e) {
var uri = 'http://www.w3.org/2000/svg';
var svg = this.$$('svg');
var circle = document.createElementNS(uri,'circle');
circle.setAttributeNS(uri, 'r', '5');
circle.setAttributeNS(uri, 'cx', e.detail.x);
circle.setAttributeNS(uri, 'cy', e.detail.y);
circle.setAttributeNS(uri, 'fill', 'white');
circle.setAttributeNS(uri, 'stroke', 'black');
circle.setAttributeNS(uri, 'stroke-width', '2');
svg.appendChild(circle);
}
});
</script>
</dom-module>
This is a test page:
<!DOCTYPE html>
<html>
<head>
<title>svg-test Demo</title>
<a href="http://../webcomponentsjs/webcomponents-lite.min.js">http://../webcomponentsjs/webcomponents-lite.min.js</a>
<link rel="import" href="svg-test.html">
</head>
<body unresolved>
<p>An example of svg-test looks like this:</p>
<svg-test></svg-test>
</body>
</html>
And this is bower.json
:
{
"name": "svg-test",
"dependencies": {
"polymer": "Polymer/polymer#^1.1.2"
}
}
Solution
Answered By: Anonymous
Although SVG elements are in the SVG namespace, attributes are typically in the null namespace so you want this…
var circle = document.createElementNS(uri,'circle');
circle.setAttribute('r', '5');
circle.setAttribute('cx', e.detail.x);
circle.setAttribute('cy', e.detail.y);
circle.setAttribute('fill', 'white');
circle.setAttribute('stroke', 'black');
circle.setAttribute('stroke-width', '2');