JSFiddle - React, Tailwind, and code Playground

by Jonathan

HTML

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/css/ol.css" type="text/css">
  <style>
    .map {
      height: 400px;
      width: 100%;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/build/ol.js"></script>
  <title>OpenLayers example</title>
</head>   
<div id="map" class="map"></div>

JavaScript

const extent = [-400, -85, 400, 85]
const textent = ol.proj.transformExtent(	
          extent,
          "EPSG:4326",
          "EPSG:3857"
        )
const canvas = document.createElement("canvas");
const vsource = new ol.source.Vector({ wrapX: false });
const vlayer = new ol.layer.Vector({source: vsource})

const pixProj = new ol.proj.Projection({
  code: "pixel-projection",
  units: "pixels",
})

const points = [[extent[0],0], [extent[0] + 100,0]].map(p =>  ol.proj.transform(p, "EPSG:4326", "EPSG:3857"))
const points2 =  [[-180,0], [0,0]].map(p =>  ol.proj.transform(p, "EPSG:4326", "EPSG:3857"))
vsource.addFeature(new ol.Feature(new ol.geom.LineString(points)))
vsource.addFeature(new ol.Feature(new ol.geom.LineString(points2)))

 var ic = new ol.source.ImageCanvas({
      ratio: 1,
      canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
  
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (let f of vsource.getFeatures()) {        
          const coords = f.getGeometry().getCoordinates();

          const pixel1 = this.map.getPixelFromCoordinate(coords[0]);              
          const pixel2 = this.map.getPixelFromCoordinate(coords[1]);

          ctx.save();
          ctx.beginPath();
          ctx.moveTo(pixel1[0],pixel1[1]);                                   
          ctx.lineTo(pixel2[0],pixel2[1]);  						 
          ctx.closePath();
          ctx.strokeStyle = "red";
          ctx.stroke() 
          ctx.restore()
      
          
        }
        return canvas;
      },
      projection: pixProj
    });
    
 
 var imageLayer = new ol.layer.Image({
      className: "annotate",
      source: ic,
      zIndex: 100
    }); 
 
 var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          vlayer,
          imageLayer
        ],
        view:  new ol.View({
       ...