也许我制作的这个例子可以帮助你,它遵循以下步骤:
- 创建画布
- 用于
CanvasRenderingContext2D
创建图像数据
- 根据你的数组修改(我在示例中使用随机值)
- 用图像数据填充画布
- 获取画布的url
- 使用网址
StaticImage
<!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>
参考: