svennergr svennergr - 1 year ago 112
Javascript Question

Problems with adding SVG clip-path attribute via JavaScript

I am currently trying to get something like a conical gradiant on a Google Gauge chart.
You can see my tries in that fiddle:

I am adding a gauge-chart and a conical gradiant at a HTML canvas.
Then I am adding a path-element to a SVG-clipPath:

This path-elements gets the path from the red bar in the gauge chart.

Finally I am creating the image-Element and adding all elements to the specifiy element in the svg.

But sadly the clip-path does not seem to work proper. I am not getting the path as expected but the whole image.

There might be some conflicts with using the right namespaces on certain functions. I would be glad if somebody could check.

google.charts.load('current', {'packages':['gauge']});
function drawChart() {

var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Test1', 80],
['Test2', 80],

var options = {
width: 400, height: 120,
redFrom: 0, redTo: 100,
minorTicks: 5

chart = new google.visualization.Gauge(document.getElementById('chart_div'));

chart.draw(data, options);

canvas = document.createElement('canvas'),
d = canvas.width = canvas.height = 200,
ctx = canvas.getContext('2d');


ctx.translate(d/2, d/2);
ctx.lineWidth = 2;
ctx.lineCap = 'round';

for(var i=0; i<=360; i++) {;

ctx.rotate(Math.PI * i/180);
ctx.translate(-ctx.lineWidth/2, ctx.lineWidth/2);

ctx.moveTo(0, 0);
ctx.strokeStyle = 'hsl(' + i + ',100%,50%)';

ctx.lineTo(0, d);


xmlns = "";

cp.setAttribute("id", "cp1");
cp.setAttributeNS(xmlns, "clipPathUnits","userSpaceOnUse");

p=document.createElementNS(xmlns, "path");
p.setAttributeNS(xmlns, "d", clipPath);
//p.setAttribute("style", "opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:3;stroke-linecap:square;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1");


img=document.createElementNS(xmlns, "image");
img.setAttributeNS('', 'href', canvas.toDataURL()+" ");
img.setAttributeNS(xmlns, "clip-path","url(#cp1)");
img.setAttribute("width", 200);
img.setAttribute("x", 0);


svgEl[0].childNodes[1].insertBefore(img, svgEl[0].childNodes[1].childNodes[3]);

<script src=""></script>
<div id="chart_div" style="width: 400px; height: 120px;"></div>

Answer Source

There are no attributes in the SVG namespace ( in SVG. Only elements are in the SVG namespace.

So for attribute setting in general you want setAttribute except for xlink:href (SVG 1.1) and the rarely used xml:space attribute (also SVG 1.1). SVG 2 will do away with both of these exceptions so that all attributes will be able to be set with setAttribute.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download