Skip to content

Instantly share code, notes, and snippets.

@mzur
Created October 24, 2018 12:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzur/d0ca83858c0f4e3bae807e1857801621 to your computer and use it in GitHub Desktop.
Save mzur/d0ca83858c0f4e3bae807e1857801621 to your computer and use it in GitHub Desktop.
OpenLayers ImageStatic with canvas source
import ImageStatic from 'ol/source/ImageStatic';
import ImageCanvas from 'ol/ImageCanvas';
import EventType from 'ol/events/EventType';
import {listen} from 'ol/events';
class Canvas extends ImageStatic {
constructor(options) {
super(options);
this.image_ = new ImageCanvas(options.imageExtent, 1, 1, options.canvas);
listen(this.image_, EventType.CHANGE, this.handleImageChange, this);
}
}
export default Canvas;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using Parcel with OpenLayers</title>
<style>
#map {
width: 400px;
height: 250px;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="./index.js"></script>
</body>
</html>
import 'ol/ol.css';
import {Map, View} from 'ol';
import ImageLayer from 'ol/layer/Image';
import ImageSource from './ImageCanvas.js';
import Projection from 'ol/proj/Projection';
import {getCenter} from 'ol/extent';
let canvas = document.createElement('canvas');
// Set dimensions of image.
canvas.width = 100;
canvas.height = 100;
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 100, 100);
let extent = [0, 0, canvas.width, canvas.height];
let projection = new Projection({
code: 'pixel-projection',
units: 'pixels',
extent: extent,
});
const map = new Map({
target: 'map',
layers: [
new ImageLayer({
source: new ImageSource({
canvas: canvas,
projection: projection,
imageExtent: extent,
}),
}),
],
view: new View({
projection: projection,
center: getCenter(extent),
// Initially, display canvas at original resolution (100%).
resolution: 1,
zoomFactor: 2,
// Allow a maximum of 4x magnification.
minResolution: 0.25,
// Restrict movement.
extent: extent,
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment