OpenLayers3添加ImageCanvas作为图层

ol3中的ImageCanvas天然就是为了让用户将Canvas画的图像添加到地图中作为图层。

下面给出代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>添加一个Canvas图层</title>
		<script type="text/javascript" src="../build/ol-debug.js" ></script>
		<link rel="stylesheet" href="../css/ol.css" />
	</head>
	<body>
		<div id="map" class="map"></div>
	    <script>
	    	var isFirst=true;//是否第一次加载该canvas图层
		var canvasOption=new Object();
		//ImageCanvas有一个canvasFunction属性
		//通过查看源代码,发现该属性其实是一个回调函数,需要对该函数进行实现,从而创建一个canvas
		//创建回调函数如下
		canvasOption.canvasFunction=function(extent, resolution, pixelRatio, size, projection){
			if(isFirst)//这里必须要做一个判断,每次的范围变动都会引起重绘,从而触发该回调函数,不判断的话,将会导致canvas无法被绘制到地图上,出现闪现的情况
			{
				isFirst=false;
				var canvas=document.createElement('canvas');
				canvas.width=size[0];
				canvas.height=size[1];
					
				var context = canvas.getContext('2d');
			      
			        context.fillStyle = "blue";
			        context.fillRect(0,0,1000,1000);
				return canvas;
			}
		};
		//为ImageCanvasLayer创建数据源
		var imageCanvas=new ol.source.ImageCanvas(canvasOption);
		//创建一个ImageCanvasLayer图层
		var imageCanvasLayer=new ol.layer.Image({
				source:imageCanvas
			});
		
	      	var layers = [
		        new ol.layer.Tile({
		          source: new ol.source.OSM()//这里使用ol自带的一个地图图层作为底图
		        }),
		        imageCanvasLayer
		      ];
		      
	      	var map = new ol.Map({
		        layers: layers,
		        target: 'map',
		        view: new ol.View({
		          center: [-10997148, 4569099],
		          zoom: 4
		        })
      		});
	    </script>
	</body>
</html>

转载自:https://blog.csdn.net/u010520626/article/details/53846288

You may also like...