Render geometries to a canvas

This example uses OpenLayers v4.0.1. The latest is v.

#### Render geometries to a canvas

Example of rendering geometries to an arbitrary canvas.

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

Related API documentation:

- ol.geom.LineString
,
- ol.geom.Point
,
- ol.geom.Polygon
,
- ol.render
,
- ol.style.Circle
,
- ol.style.Fill
,
- ol.style.Stroke
,
- ol.style.Style

Copy Edit
Render geometries to a canvas Example of rendering geometries to an arbitrary canvas. var canvas = document.getElementById('canvas'); var vectorContext = ol.render.toContext(canvas.getContext('2d'), {size: [100, 100]}); var fill = new ol.style.Fill({color: 'blue'}); var stroke = new ol.style.Stroke({color: 'black'}); var style = new ol.style.Style({ fill: fill, stroke: stroke, image: new ol.style.Circle({ radius: 10, fill: fill, stroke: stroke }) }); vectorContext.setStyle(style); vectorContext.drawGeometry(new ol.geom.LineString([[10, 10], [90, 90]])); vectorContext.drawGeometry(new ol.geom.Polygon([[[2, 2], [98, 2], [2, 98], [2, 2]]])); vectorContext.drawGeometry(new ol.geom.Point([88, 88])); <canvas id="canvas"></canvas>

    <!DOCTYPE html>
    <html>
      <head>
        <title>Render geometries to a canvas</title>
        <link rel="stylesheet" href="https://openlayers.org/en/v4.0.1/css/ol.css" type="text/css">
        <!-- 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>
        <script src="https://openlayers.org/en/v4.0.1/build/ol.js"></script>
      </head>
      <body>
        <canvas id="canvas"></canvas>
        <script>
          var canvas = document.getElementById('canvas');
          var vectorContext = ol.render.toContext(canvas.getContext('2d'), {size: [100, 100]});

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

          vectorContext.drawGeometry(new ol.geom.LineString([[10, 10], [90, 90]]));
          vectorContext.drawGeometry(new ol.geom.Polygon([[[2, 2], [98, 2], [2, 98], [2, 2]]]));
          vectorContext.drawGeometry(new ol.geom.Point([88, 88]));
        </script>
      </body>
    </html>