0

I want to fill a set of polygons with png pattern.

Here is an extract of my code :

 var canvas = document.createElement('canvas');
 var context = canvas.getContext('2d');
 var pattern;
 var imageObj = new Image();

 imageObj.src = data["fichier_hachures"];

 imageObj.onload = function() {
     pattern = context.createPattern(imageObj, 'repeat');
 };

  zonageItems.push(new ol.layer.Vector({
        source: vectorSource,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: pattern
            })
        })
  })
);

When I do this I get my polygons filled with black color.

data["fichier_hachures"] : is an object property containing the Base64 string of my png image.

1

Borrowing code from this other answer, I'm able to provide base64 image content to show a pattern (demo)

The issue in my opinion seems to be the fact, you make a call to

zonageItems.push(new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: pattern
        })
    })
})

outside of imageObj.onload function. Due to this, at the moment, you make a call to an image pattern not already loaded because async (hence your black result)

Did you try instead

imageObj.onload = function() {
    pattern = context.createPattern(imageObj, 'repeat');
    zonageItems.push(new ol.layer.Vector({
        source: vectorSource,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: pattern
            })
        })
    })
};
  • Thank you @ThomasG77, after some edits it's now working. – M.usf Oct 22 '18 at 10:43
  • Just curious, what was the real issue at the end? – ThomasG77 Oct 23 '18 at 17:34
  • It was a basic issue with variables declaration. – M.usf Oct 24 '18 at 13:51
  • Now I am facing another issue. I have multiple polygons each one with its own png pattern. But all polygons are displayed with the same png pattern. I believe that is caused by the asynchronous image loading. Any idea to fix this problem ? – M.usf Oct 24 '18 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.