I'm drawing a rectangular feature onto a map layer. I have some image pattern I want to display as a background of the feature and I want the pattern to scale with the map when zooming, meaning the pattern has always the same looking background, no matter the zoom level.
What I have right now displays the background for the feature, but it doesn't scale with the feature when zooming:
const imageData = "..."; // some base64 encoded image pattern
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const img = new Image();
img.onload = function () {
var pattern = context.createPattern(img, 'repeat');
const style = new Style({
fill: new Fill({
color: pattern,
}),
});
feature.setStyle(style);
};
img.src = imageData;
I'm adding the features to a VectorLayer to display them on the map:
const vectorLayer = new VectorLayer({
source: new VectorSource({
features: features,
}),
updateWhileAnimating: true,
});
What I tried to do is wrapping the code with reaction on resolution change and scaling the pattern, but I don't really know how to scale it properly, so that the background just stays the same relative to the pattern?
map.getView().on('change:resolution', function() {
const resolution = this.getResolution();
....
pattern.setTransform(new DOMMatrix().scale(1 / resolution, 1 / resolution)); // ??
Very much like the Style Render example https://openlayers.org/en/latest/examples/style-renderer.html except that instead of using flag images you would create a canvas image (big enough for the largest feature) filled with your pattern and use that. In the example the flags can be seen to move relative to the country outlines as they are panned partially out of the view. That can be prevented by setting a large
renderBufferon the layer. https://codesandbox.io/s/style-renderer-forked-tvnq7r?file=/main.jsWorking example: