[GIS] Fill polygon with SVG image pattern

fillopenlayerspolygonstyle

I want to fill my polygons in openlayers 3 to make them look like this:
enter image description here

In QGIS I can provide a svg image to create this kind of pattern. How can this be achieved in openlayers 3?

Background / Research so far

I intensively read through the API documentation and found out that the ol.style.Fill class accepts an ol.ColorLike object.
A ol.ColorLike Object again accepts a CanvasRenderingContext2D.fillStyle, which can be an image pattern or a gradient. So I guess it should be technically possible to tweak the openlayers API to achieve a patterned polygon fill.

See these links for further information:

  1. http://openlayers.org/en/latest/apidoc/ol.style.Fill.html
  2. http://openlayers.org/en/latest/apidoc/ol.colorlike.html
  3. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle
  4. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createPattern

Putting the Pieces together

This is my code so far and here begins the trouble. I can't find a way to get a working instance of CanvasRenderingContext2D. It always returns with undefined.

var canvas = document.getElementsByClassName('ol-unselectable') // filter <canvas>
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
var colorLike;

img.onload = function() {
      var pattern = CanvasRenderingContext2D.createPattern(img, 'repeat');
      CanvasRenderingContext2D.fillStyle = pattern;
      colorLike = CanvasRenderingContext2D.fillStyle
}  

var style = new ol.style.Style({

      fill: new ol.style.Fill({
           color: colorLike // ol.ColorLike object
      })
  })

To see the full code visit: jsfiddle

Is there a way to access the polygon drawing canvas prior initializing it? Or how can I create a correct CanvasRenderingContext2D instance here?

Best Answer

ok, sometimes you don't realize that you're almost at the finish line...following SE Question pointed me into the right direction and after adding some lines of code it now works :)

Working Example:

var geojsonObject = 'someGeoJSON' 
var source = new ol.source.Vector({
   features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
  });

var layer = new ol.layer.Vector({
source: source
});

var cnv = document.createElement('canvas');
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function() {
  var pattern = ctx.createPattern(img, 'repeat');
  layer.setStyle(new ol.style.Style({
    fill: new ol.style.Fill({
      color: pattern
    })
  }));
};

Full working example: jsfiddle