如何在OpenLayers中使用图像填充图层? [英] How do I use an image to fill a layer in OpenLayers?

查看:456
本文介绍了如何在OpenLayers中使用图像填充图层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OpenLayers绘制地图,我想用来自那个国家的照片填充描述一个国家的多边形.我知道我可以将CanvasPattern传递给ol.style.Fillcolor,但是我不知道生成图像.

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.

这是我的代码,还有一个带有完整示例的JSfiddle: http://jsfiddle.net/07366L44/5/

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');
}

我认为是因为照片被异步加载.其他示例在photo.onload方法中创建模式,但我不知道如何返回该模式.

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!

推荐答案

您必须在图像的onload处理程序中设置样式的填充颜色.

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';
}

请注意,在调用样式函数之前需要设置填充的颜色,因此您不能在样式函数中调用setPattern函数.最好在加载图层之前先创建样式.

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.

这篇关于如何在OpenLayers中使用图像填充图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆