I want to fill my polygons in openlayers 3 to make them look like this:
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:
- http://openlayers.org/en/latest/apidoc/ol.style.Fill.html
- http://openlayers.org/en/latest/apidoc/ol.colorlike.html
- https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle
- 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?