OL3 - Fill image pattern
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/ol3/3.15.1/ol.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/ol3/3.15.1/ol.css">
<div id="map" class="map"></div>
CSS
html, body, .map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
border: 0;
}
JavaScript
var featurePoly = new ol.Feature(new ol.geom.Polygon([[
[-12550727, 2281352], [-11168471, 3244427],
[-10867077, 1986886], [-12550727, 2281352]
]]));
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
// create the off-screen canvas
var canvasPattern = document.createElement("canvas");
canvasPattern.width = 10;
canvasPattern.height = 20;
var contextPattern = canvasPattern.getContext("2d");
// draw pattern to off-screen context
contextPattern.fillStyle = 'red';
contextPattern.fillRect(0, 0, 20, 10);
//contextPattern.rotate(130);
// now pattern will work with canvas element
var pattern = context.createPattern(canvasPattern, "repeat");
featurePoly.setStyle(new ol.style.Style({
fill: new ol.style.Fill({
color: pattern /* works well */
})
}));
var vectorSource = new ol.source.Vector({
features: [featurePoly]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({ source: new ol.source.OSM() }),
vectorLayer
],
view: new ol.View({
center : [-11407508, 2520388],
zoom : 3
})
});