1. 程式人生 > >Openlayers圖片資源source裡的imageCanvas裡的canvasFunction屬性回撥函式

Openlayers圖片資源source裡的imageCanvas裡的canvasFunction屬性回撥函式

<!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圖層

//為ImageCanvasLayer建立資料來源
//ImageCanvas有一個canvasFunction屬性,其值是一個回撥函式
var imageCanvas=new ol.source.ImageCanvas({
    //建立回撥函式如下
    canvasFunction:render({log:10,lat:20});
});

function render(data){
    //引數1:extent array 左下角投影座標與右上角投影座標
    //引數2:resolution 要生產影象的解析度
    //引數3:裝置畫素比
    //引數4:影象實際大小
    //引數5:投影
    return function(extent, resolution, pixelRatio, size, projection){
     //每次的範圍變動都會引起重繪,從而觸發該回調函式,
        var [width, height] = size; //畫布尺寸
        var [left, bottom, right, top] = extent; //座標投影
        var xScale = width / (right - left); //畫布尺寸與座標投影比
        var yScale = height / (top - bottom);

        var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
        ;
        

        var canvas=document.createElement('canvas');
        canvas.width=width;
        canvas.height=height;
                    
        var ctx = canvas.getContext('2d');
        var [lon, lat] = transform([data.lon,data.lat]);
        //傳進來的座標轉為canvas上的點(x,y)
        var x = (lon - left) * xScale; //轉換成手機次尺寸的xy
        var y = (top - lat) * yScale
        ctx.beginPath();
        ctx.arc(x, y, 150 * pixelRatio, 0, 2*Math.PI);          
        ctx.fillStyle = "blue";
        ctx.fill();//畫原圓點
        return canvas;
    }
};

//建立一個ImageCanvasLayer圖層
var imageLayer=new ol.layer.Image({
        source:imageCanvas
    });
        
var layers = [
        new ol.layer.Tile({
            source: new ol.source.OSM()//這裡使用ol自帶的一個地圖圖層作為底圖
        }),
        imageLayer
    ];
              
var map = new ol.Map({
    layers: layers,
    target: 'map',
    view: new ol.View({
          center: [-10997148, 4569099],
          zoom: 4
    })
  });
</script>
</body>
</html>