将 OpenLayers Canvas 源与静态图像一起使用

Use OpenLayers Canvas source with Image static

我一直在尝试使用 OpenLayers (v6.1.1) 在 Canvas 上进行绘制,但不幸的是,我在 Canvas 实现方面遇到了困难。

我试过这个简单的方法:

const extent = [0, 0, 1024, 968];

const projection = new ol.proj.Projection({
  code: 'pixel-projection',
  units: 'pixels',
  extent: extent,
});

let canvas = document.createElement('canvas');

canvas.width = 1024;
canvas.height = 968;
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 100, 100);

const imageLayer = new ol.layer.Image({
  source: new ol.source.ImageCanvas({
    canvas: canvas,
    projection: projection,
    imageExtent: extent,
  }),
});

但我收到一个未定义的错误:

此外,这里有一个 fiddle 以便于导航: https://jsfiddle.net/Loque/ur5gw270/4/

非常感谢任何帮助,谢谢。

ImageCanvas 需要一个 canvasFunction 选项:

  source: new ol.source.ImageCanvas({
    canvasFunction: function() {
      return canvas;
    },
    projection: projection,
    imageExtent: extent,
    ratio: 1,
  }),

ImageStatic 需要一个 url 选项:

  source: new ol.source.ImageStatic({
    url: canvas.toDataURL(),
    projection: projection,
    imageExtent: extent,
  }),