ScreenshotNeo

BlogHow-to

How to Use an Esri Proxy to Capture Angular 7 Maps as Screenshots

Configure an Esri proxy in Angular 7, capture ArcGIS maps with html2canvas, and switch to server-side export when browser rendering fails.

By the ScreenshotNeo team30 September 20269 min read

How to Use an Esri Proxy to Capture Angular 7 Maps as Screenshots

Direct answer: deploy the Esri proxy on a web server you control, configure the ArcGIS JavaScript SDK before the map makes its first request, wait for the Angular 7 MapView to finish rendering, then pass the map container to html2canvas. A proxy cannot be configured as an Esri-hosted magic endpoint: it is your application server forwarding approved ArcGIS requests. If a browser capture still misses layers, use the map service export REST operation through a MapImageLayer for a server-rendered image.

CORS is preferable when every service supports it. Use a proxy when a service lacks usable CORS, when your browser workflow needs one same-origin route, or when WebGL map images must become same-origin, CORS-enabled, or proxied. Esri recommends a proxy fallback when you are unsure whether all services support CORS.

1. How the capture pipeline works

  1. List every service origin used by the map: basemap, vector or raster tiles, feature services, map-image services, fonts, and any custom overlays.
  2. Check CORS support for each origin. A single non-CORS image can taint the canvas.
  3. Install an Esri resource proxy on your own web server and restrict its allowed targets.
  4. Set the SDK request configuration before creating layers or starting requests.
  5. Wait for the intended extent, labels, popups, and overlays to render.
  6. Capture the map element with html2canvas, then export a PNG, JPEG, or blob.
  7. Inspect network requests and the generated dimensions. If the result is incomplete, use server-side map export.

Esri’s proxy documentation states that the proxy runs on your own web server, not on an Esri server. The JavaScript Maps SDK documentation also describes global proxy configuration and URL-prefix rules. See the Esri proxy guide and Esri CORS guidance.

The browser capture path: configure the proxy, render the map, then export the container.
The browser capture path: configure the proxy, render the map, then export the container.

2. Deploy and secure the Esri proxy

Choose the proxy implementation that matches your server stack. Esri documents Java/JSP, PHP, and ASP.NET resource proxies. Deploy it under your application origin, for example https://maps.example.com/proxy/Java/proxy.jsp, and verify that the route is reachable from the browser.

Proxy security checklist

  • Allow only the ArcGIS domains and service paths your application needs.
  • Require HTTPS and avoid exposing upstream credentials in client-side code.
  • Apply authentication and rate limits at the proxy or upstream service.
  • Reject arbitrary forwarding and validate query strings.
  • Log failures without logging access tokens or sensitive headers.
  • Test the proxy with a known service URL before wiring Angular.

An unrestricted forwarding endpoint can become an abuse path. Follow Esri’s proxy security and authentication guidance for the implementation you deploy.

3. Configure proxyUrl in an Angular 7 application

The exact import path depends on whether Angular 7 uses the ArcGIS JavaScript SDK’s AMD loader or a wrapper. The important rule is ordering: set the request configuration before the first layer request.

AMD-style startup configuration

declare const require: any;

require([
  "esri/config",
  "esri/Map",
  "esri/views/MapView",
  "dojo/domReady!"
], (esriConfig: any, Map: any, MapView: any) => {
  // Set this before creating layers or a view that will request them.
  esriConfig.request.proxyUrl = "/proxy/Java/proxy.jsp";

  const map = new Map({
    basemap: "streets-vector"
  });

  const view = new MapView({
    container: "mapView",
    map,
    center: [-98.5, 39.8],
    zoom: 4
  });

  view.when(() => {
    console.log("Map and view are ready");
  });
});

Selective URL-prefix rules

A global proxy is simple, but a URL-prefix rule lets you proxy only services that need it. Keep the rule before the first request to that service.

esriConfig.request.proxyRules = [
  {
    urlPrefix: "https://services.example.com/arcgis/rest/services",
    proxyUrl: "/proxy/Java/proxy.jsp"
  }
];

Use the SDK generation’s documented request configuration shape. Do not mix configuration APIs from an older ArcGIS sample with the SDK version loaded by your Angular application.

4. Complete Angular 7 capture example with html2canvas

This example waits for the view, optionally waits for layer readiness, and downloads the resulting canvas. Install the library with npm install html2canvas.

import { Component, NgZone, OnInit } from "@angular/core";
import html2canvas from "html2canvas";

declare const require: any;

@Component({
  selector: "app-map-capture",
  template: `
    <button type="button" (click)="capture()" [disabled]="!ready">
      Download map PNG
    </button>
    <div id="mapView" class="map-view"></div>
  `,
  styles: [`
    .map-view { width: 900px; height: 600px; }
  `]
})
export class MapCaptureComponent implements OnInit {
  ready = false;
  private view: any;

  constructor(private zone: NgZone) {}

  ngOnInit(): void {
    require([
      "esri/config",
      "esri/Map",
      "esri/views/MapView",
      "dojo/domReady!"
    ], (esriConfig: any, Map: any, MapView: any) => {
      esriConfig.request.proxyUrl = "/proxy/Java/proxy.jsp";

      const map = new Map({ basemap: "streets-vector" });
      this.view = new MapView({
        container: "mapView",
        map,
        center: [-98.5, 39.8],
        zoom: 4
      });

      this.view.when(() => {
        this.zone.run(() => { this.ready = true; });
      });
    });
  }

  async capture(): Promise<void> {
    if (!this.view) return;

    // Ensure the map has drawn the current extent before DOM reconstruction.
    await this.view.when();
    await this.view.whenLayerView(this.view.map.layers.getItemAt(0)).catch(() => undefined);

    const element = document.getElementById("mapView");
    if (!element) throw new Error("Map container was not found");

    const canvas = await html2canvas(element, {
      useCORS: true,
      allowTaint: false,
      backgroundColor: "#ffffff",
      scale: window.devicePixelRatio || 1,
      logging: false
    });

    const link = document.createElement("a");
    link.download = "angular-arcgis-map.png";
    link.href = canvas.toDataURL("image/png");
    link.click();
  }
}

For production code, wait for the layers that matter to your capture rather than assuming item zero exists. You can also wait for a specific selector, a known rendering state, or a short delay after a viewpoint change.

5. html2canvas options and browser limits

html2canvas documentation explains that it reconstructs an image from DOM information; it does not take a literal GPU screenshot. Therefore the output can differ from the live map.

Option or limit Use Failure mode
useCORS: true Request image resources with CORS when the server sends the required headers. It cannot fix a server that does not permit your origin.
proxy Route supported cross-origin image resources through a same-origin html2canvas proxy. The proxy must return the image with a usable content type and must be secured.
allowTaint: false Prevent export when an image would taint the canvas. toDataURL or toBlob fails until the resource is CORS-enabled or proxied.
scale Control output pixel density. A device-pixel ratio of 2 doubles each dimension. Memory use grows with pixel area.
Cross-origin iframe Not renderable by DOM reconstruction. Browser security prevents access to the iframe’s document.
WebGL layers Require same-origin, CORS-enabled, or proxied images for readable pixels. Canvas export can be blank or throw a security error.

6. Capturing a specific map state

  • Set the viewpoint before capture and await the view’s update completion.
  • Close or open popups intentionally; html2canvas captures what is visible in the container.
  • Hide controls, attribution, or scale bars with a CSS class if they should not appear.
  • Use a fixed width and height for repeatable output.
  • For full-page output, capture a dedicated map-sized wrapper rather than the entire application shell.
async function waitForView(view: any): Promise<void> {
  await view.goTo({ center: [-73.9857, 40.7484], zoom: 12 });
  await view.when();
  // The view updates while tiles and layers arrive; wait for the current draw cycle.
  await new Promise(resolve => setTimeout(resolve, 500));
}

async function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob> {
  return new Promise((resolve, reject) => {
    canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Canvas export failed")), "image/png");
  });
}

7. When client capture fails: server-rendered map export

Use the ArcGIS map service export REST operation when you need reliable handling of cross-origin layers, large dimensions, or server-side authentication. A MapImageLayer can expose the map service that performs the render. This avoids depending on DOM reconstruction and the browser’s canvas security rules.

When DOM capture is incomplete, a map service export renders the image on the server.
When DOM capture is incomplete, a map service export renders the image on the server.
require([
  "esri/layers/MapImageLayer"
], (MapImageLayer: any) => {
  const layer = new MapImageLayer({
    url: "https://services.example.com/arcgis/rest/services/CityMap/MapServer"
  });

  layer.exportImage({
    bbox: "-8239000,4960000,-8230000,4970000",
    size: { width: 1600, height: 1000 },
    format: "png32",
    transparent: true
  }).then((image: any) => {
    const img = document.createElement("img");
    img.src = image.url;
    document.body.appendChild(img);
  });
});

Use the service’s documented export parameters for spatial reference, layer visibility, time extent, image format, and authentication. Compare approaches by pixel fidelity, cross-origin handling, credential exposure, output dimensions, browser-rendering dependence, and implementation complexity.

8. Troubleshooting

Symptom Likely cause Fix
Proxy requests never appear Configuration was set after the layer request. Set proxyUrl or proxy rules before creating the map and layers.
Proxy URL returns 404 The deployed path differs from the SDK configuration. Open the exact proxy URL directly, fix the web-server route, and check the browser network panel.
Map loads but export throws a security error A tile or image lacks CORS and was not proxied. Find the failing origin in network requests; enable CORS, add a selective proxy rule, or use server export.
Canvas is blank Capture started before the view or WebGL layer rendered, or the layer is cross-origin. Await view.when(), wait for the relevant layer view, then verify CORS/proxy headers.
Labels or popups are missing DOM reconstruction captured an earlier state or an element outside the target container. Set the desired state first, wait for rendering, and capture a wrapper that contains the overlays.
Cross-origin iframe is empty Browser policy blocks access to its document. Capture the iframe’s own page with cooperation from that origin, or use a server-side renderer/export.
Credentials leak in the browser Tokens or upstream credentials were embedded in client code. Move credentialed requests behind the secured proxy or server export endpoint.
Output is too large or crashes the tab High scale multiplied a large canvas’s pixel area. Lower scale, reduce dimensions, capture in tiles, or render on the server.
Only some layers are absent One service origin lacks CORS or is not covered by a proxy prefix. Inventory every origin and add rules for each required service.

9. Performance, reliability, and cost considerations

  • Browser work: large viewports, retina scale, many labels, and WebGL layers increase memory and rendering time.
  • Network work: a proxy adds a server hop. Keep it near your application, reuse connections, and avoid routing services that already provide correct CORS.
  • Repeatability: wait for a stable viewpoint and layer state; asynchronous tiles can otherwise produce different images.
  • Reliability: server export is easier to retry and audit because it does not depend on a user’s browser, iframe policy, or GPU state.
  • Security: restrict proxy targets, protect credentials, and rate-limit forwarding.
  • Cost: self-hosted capture consumes browser/server resources and any ArcGIS service quota. A screenshot API can move browser setup and retry handling out of your application; check its pricing and billing rules before choosing it.

10. Or skip the browser setup

ScreenshotNeo provides a single GET request for a PNG, JPEG, WebP, or PDF. It removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

For a public map page, call the API directly:

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://your-app.example.com/map \
  -o map.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://your-app.example.com/map"},
    timeout=90,
)
r.raise_for_status()
open("map.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://your-app.example.com/map'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('map.webp', bytes);

See the ScreenshotNeo API documentation for the available capture options. You get 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

11. FAQ

Is an Esri proxy required for every Angular map?

No. Use direct CORS when every service supports it. Add a proxy when a service or browser workflow cannot provide usable CORS.

Can html2canvas capture the ArcGIS WebGL canvas exactly?

No. It reconstructs the DOM and cannot guarantee a pixel-identical GPU screenshot. Cross-origin resources can also make the canvas unreadable.

Where should proxy configuration live?

At application startup, before the first request that needs proxying. A late assignment cannot rewrite requests that already started.

Should I proxy all ArcGIS requests?

Only when needed. Selective URL-prefix rules reduce unnecessary server hops; global proxying is simpler when your services share the same requirements.

When is MapImageLayer export the better choice?

Choose it when browser capture is incomplete, when you need predictable dimensions, or when server-side credentials and rendering are required.