Search code examples
html5-canvasleafletextend

Leaflet extending canvas


I'm trying to extend the canvas in Leaflet 1.4 like this:

L.Canvas.FPCanvas = L.Canvas.extend({
  options: {
    width: 1,
    height: 1
  },

  initialize: function(name, options) {
    this.name = name;
    L.setOptions(this, options);
  },

  onAdd: function (map){},

  onRemove: function (map) {}
});

L.canvas.fpCanvas = function(id, options) {
  return new L.Canvas.FPCanvas(id, options)
}

console.log(L.canvas.fpCanvas("fpCanvas", {width: 10, height: 10}))

const myRenderer = L.canvas();
console.log(myRenderer)

When I log my extended canvas to the console everything up the prototype chain looks good. However when I log the code below:

const myRenderer = L.canvas();
console.log(myRenderer)

_layers: {}
_leaflet_id

These two additional properties appear, while I was expecting them to be the same. How do I modify my canvas extend to include these additional properties, assuming I need them to work with extended custom canvas. Thanks


Solution

  • You're replacing the L.Canvas.initialize() implementation with your own - therefore, the default initialization is not happening.

    Let me quote from the Leaflet tutorial on class extension:

    Calling a method of a parent class is achieved by reaching into the prototype of the parent class and using Function.call(…). This can be seen, for example, in the code for L.FeatureGroup:

    L.FeatureGroup = L.LayerGroup.extend({
    
        addLayer: function (layer) {
            …
            L.LayerGroup.prototype.addLayer.call(this, layer);
        },
    
        …
    });
    

    Calling the parent’s constructor is done in a similar way, but using ParentClass.prototype.initialize.call(this, …) instead.