Search code examples
javascriptopenlayers

How do I use an image to fill a layer in OpenLayers?


I'm using OpenLayers to draw a map, and I'd like to fill the polygon that describes a country with a photo from that country. I know I can pass a CanvasPattern to ol.style.Fill's color, but I don't know to generate an image.

Here's my code, and a JSfiddle with a full example: http://jsfiddle.net/07366L44/5/

function getPhoto() {
    var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var photo = new Image();
  photo.src = 'http://i.imgur.com/C6PL9tB.jpg';

  return context.createPattern(photo, 'repeat');
}

I think it's because the photo is loaded async. Other examples create the pattern in the photo.onload method but I don't know how to return that.

Optimally I'd like to return a canvas which I can animate or update later with other photos, but I'll settle for just a single static image per country!


Solution

  • You'll have to set your style's fill color in the image's onload handler.

    /**
     * @param {ol.style.Style} style Style to set the pattern on.
     */
    function setPattern(style) {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      var photo = new Image();
      photo.onload = function() {
        canvas.width = photo.width;
        canvas.height = photo.height;
        var pattern = context.createPattern(photo, 'repeat');
        style.getFill().setColor(pattern);
      }
      photo.src = 'http://i.imgur.com/C6PL9tB.jpg';
    }
    

    Note that the fill's color needs to be set before the style function is called, so you cannot call the setPattern function in the style function. It's better to create the style before loading the layer.