I am trying to create a raster grid from an array of data and display the layer in OpenLayers. I have found an example but it is for OpenLayers v2, and I cannot figure how to do it with latest version of OpenLayers (5 or 6).
Example with OpenLayers 2: http://dev.openlayers.org/sandbox/august/trunk/playground/raster/raster-array.html
I know the extent of the raster I want to create and the cell size and projection. The idea is to create the raster layer from scratch internally with the values from an javascript array, and ultimately display the map as an image setting colors based on the values. I think I can use raster. Operation to create the final image (rgb value based on the raster value), but I cannot find how to do the first step; create the raster grid with the values from an array.
Maybe this example that I made can help you, it follows the next steps:
CanvasRenderingContext2D
to create the image dataStaticImage
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
#a { display: none; }
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<title>Array Image</title>
</head>
<body>
<h2>Array Image</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
// Map views always need a projection. Here we just want to map image
// coordinates directly to map coordinates, so we create a projection that uses
// the image extent in pixels.
var width = 1024;
var height = 968;
var extent = [0, 0, width, height];
var projection = new ol.proj.Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent
});
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var canvas = document.createElement('canvas');
// canvas.width = width;
// canvas.height = height;
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < imageData.data.length; i += 4) {
// Modify pixel data
imageData.data[i + 0] = getRandomInt(255); // R value
imageData.data[i + 1] = getRandomInt(255); // G value
imageData.data[i + 2] = getRandomInt(255); // B value
imageData.data[i + 3] = 255;// getRandomInt(255); // A value
}
// Draw image data to the canvas
ctx.putImageData(imageData, 0, 0);
var dataURL = canvas.toDataURL();
var map = new ol.Map({
layers: [
new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: '© <a href="http://xkcd.com/license.html">xkcd</a>',
url: dataURL,
projection: projection,
imageExtent: extent
})
})
],
target: 'map',
view: new ol.View({
projection: projection,
center: ol.extent.getCenter(extent),
zoom: 2,
maxZoom: 8
})
});
</script>
</body>
</html>
References: