Edit

Render geometries to a canvas

Example of rendering geometries to an arbitrary canvas.

This example shows how to render geometries to an arbitrary canvas.

index.html<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Render geometries to a canvas</title>
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="index.js"></script>
  </body>
</html>
index.jsimport 'ol/ol.css';
import {LineString, Point, Polygon} from 'ol/geom';
import {toContext} from 'ol/render';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';


var canvas = document.getElementById('canvas');
var vectorContext = toContext(canvas.getContext('2d'), {size: [100, 100]});

var fill = new Fill({color: 'blue'});
var stroke = new Stroke({color: 'black'});
var style = new Style({
  fill: fill,
  stroke: stroke,
  image: new CircleStyle({
    radius: 10,
    fill: fill,
    stroke: stroke
  })
});
vectorContext.setStyle(style);

vectorContext.drawGeometry(new LineString([[10, 10], [90, 90]]));
vectorContext.drawGeometry(new Polygon([[[2, 2], [98, 2], [2, 98], [2, 2]]]));
vectorContext.drawGeometry(new Point([88, 88]));
package.json{
  "name": "render-geometry",
  "dependencies": {
    "ol": "6.1.1"
  },
  "devDependencies": {
    "parcel": "1.11.0"
  },
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --experimental-scope-hoisting --public-url . index.html"
  }
}