我需要从OSM上添加的“图像”层获取像素颜色。
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
x=e.x;
y=e.y; useCanvas(canvas,img,function(){
// get image data
var p = canvas.getContext('2d')
.getImageData(x, y, 1, 1).data;
var coord = '<span>HEX: #'+rgbToHex(p[0],p[1],p[2])+'</span>'+
'<span> RGB: rgb('+
p[0]+','+
p[1]+','+
p[2]+')</span>';
$('#status').html(coord);
答案 0 :(得分:0)
layer.getTileData(point)
将为您提供任何地图坐标的图像和图像上的位置。 data.tile.getCanvasContext()
为您提供图像的画布上下文。它应适用于任何栅格图层,无论是单个图像还是平铺网格。如果要访问像素数据,请指定tileOptions: { crossOriginKeyword: 'anonymous' }
。
//
function rgbToHex(rgb){
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
var map, layer;
function init(){
map = new OpenLayers.Map('map', { projection: 'EPSG:4326' });
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
'https://neo.sci.gsfc.nasa.gov/wms/wms',
{ layers: 'BlueMarbleNG' },
{ tileOptions: { crossOriginKeyword: 'anonymous' } }
);
map.addLayer(layer);
map.zoomToMaxExtent();
map.events.register("mousemove", map, function(e){
document.getElementById("docs").innerHTML = '';
var point = map.getLonLatFromViewPortPx(e.xy);
var data = layer.getTileData(point);
if (data) {
var ctx = data.tile.getCanvasContext();
if (ctx) {
var x = data.i;
var y = data.j;
// get image data
var p = ctx.getImageData(x, y, 1, 1).data;
document.getElementById("docs").innerHTML = '<span> HEX: '+ rgbToHex(p)+'</span>' +
'<span> RGB: rgb(' + p[0] + ',' + p[1] + ',' + p[2] + ')</span>';
}
}
});
}
init();
html, body { height: 100%; margin: 0;}
#map { height: 80%; margin: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.12/OpenLayers.js"></script>
<div id="map" class="map"></div>
<pre id="docs"></pre>