Sebastian Rehm
Sebastian Rehm

Reputation: 390

Gradient fill for circle in Leaflet

I am looking for a way to create a circle with a gradient fill in Leaflet. My approach so far is to define the fillColor of the circle as 'url(#gradient)' and add the Gradient definition manually via the following code:

function createGradient (map) {
  // Get the SVG element from the overlayPane
  var svg = map.getPanes().overlayPane.firstChild;
  var doc = document.implementation.createDocument(null, null, null);
      // Create def element
  var svgDef = doc.createElement('defs');
      // Create gradient and stops element
  var svgGradient = doc.createElement("radialGradient");
  var svgStart = doc.createElement('stop');
  var svgStop = doc.createElement('stop');

  // Set ID attribute of gradient
  svgGradient.setAttribute('id', 'gradient');

  // set stops and colors
  svgStart.setAttribute('offset', '0%');
  svgStop.setAttribute('offset', '100%');
  svgStart.setAttribute('class', 'circle-start');
  svgStop.setAttribute('class', 'circle-stop');

  svgGradient.appendChild(svgStart);
  svgGradient.appendChild(svgStop);
  // Append blur element to filter element
  svgDef.appendChild(svgGradient);
  // Append filter element to SVG element
  svg.appendChild(svgDef);
}

The funny thing is, that the gradient fill is not shown initially. However, if I go into devtools and remove the 'defs' block and add it again it the gradient fill is shown correctly. Can anyone help me to get rid of this issue or alternatively another way to get a gradient fill?

Upvotes: 2

Views: 2204

Answers (1)

Robert Longson
Robert Longson

Reputation: 124059

You cannot create SVG elements using createElement, that's only for html elements. If you want to create an SVG element you must create an element in the SVG namespace using createElementNS i.e.

var svgDef = doc.createElementNS('http://www.w3.org/2000/svg', 'defs');
    // Create gradient and stops element
var svgGradient = doc.createElementNS("http://www.w3.org/2000/svg", "radialGradient");
var svgStart = doc.createElementNS('http://www.w3.org/2000/svg', 'stop');
var svgStop = doc.createElementNS('http://www.w3.org/2000/svg', 'stop');

Using devtools reruns the html parser on the content which magically corrects the namespace.

Upvotes: 3

Related Questions