Harold
Harold

Reputation: 68

Styling the stroke of a geometry with a canvaspattern

I would like to style the stroke of a polygon in a way like this: Polygon with pattern styled stroke

The repeating image in png format looks like this: symbol

I have tried:

1) Create a CanvasPattern of the image (this is the symbol in png format).

2) Assign the pattern to the color of ol.style.Stroke.

Step 1 went well.

But step 2 is not working, since the color attribute of ol.style.Stroke should be of type ol.Color, despite the documentation of Openlayers where the color of ol.style.Stroke could also be ol.ColorLike, which means that also CanvasPattern should be allowed.

Maybe someone knows another way to accomplish the same thing?

By the way, I can fill the polygon by assigning the created CanvasPattern of the symbol, to the color of ol.style.Fill. However, in this way I am filling the polygon with the symbol; I just want the stroke to have a pattern. The "strange" thing here is, is that the attribute color of ol.style.Fill is of the same type as ol.style.Stoke, according the documentation. Anyway, any help is appreciated.

Upvotes: 0

Views: 1336

Answers (1)

Viglino Jean-Marc
Viglino Jean-Marc

Reputation: 1421

A pattern can be used as stoke color as well.

// Create pattern on image load
var image = new Image();
image.onload = function() {
  var ctx = document.createElement('canvas').getContext("2d");
  var pattern = ctx.createPattern(image,"repeat");
  // create style with the pattern
  var style = new ol.style.Style({
    stroke: new ol.style.Stroke({
      width: 8,
      color: pattern
    })
  });
  // use it on vector layer
  vector.setStyle(style);
};
// Load image
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAMAAAAolt3jAAAAGFBMVEUAAACPjwCmpgCbmwCCggD+/gCXlwD//wDWAMTYAAAAB3RSTlOAsr64rP62hR4cWgAAADpJREFUCNetzTEOACAIA8ACYv//YwVJxF0mLm0AJAUxtjeCPq6IkvKwNYM9c/ko1AdLTLxNtEyZbFcWKysC1htDphIAAAAASUVORK5CYII='

See example: https://codepen.io/viglino/pen/erErXb

Upvotes: 4

Related Questions