Related
I saw an example of "Render geometries to a 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]));
But what to do with the geometry in the projection EPSG:4326 (or EPSG:3857)?
PS
I saw the question "How can we render an OpenLayers 3 feature to a canvas using a style but not using a map", but I don't understand what projection the code works with. And to clarify the author does not allow me to low reputation on stackoverflow.
The HTML canvas element is used to draw graphics, on the fly, via JavaScript.
If your drawing in a canvas there is no more projection anymore, you're in pixel coordinate. You'll have to transform your geometry in pixel.
See the map's getPixelFromCoordinate function if you're drawing in the map canvas.
#Catch I dug in a little. In that answer he uses canvas.width (in pixels) and ol.extent.getWidth(extent) /height. ol.Extent is only array of numbers and don't have any information about coordinate system. If you would use geographic coordinates it would work with them like they are carthesian. So it depends on what area you want to diplay, but I would recomend to tranform it to some projection and then use the advised approach - translate, scale, translate (scale is now supported in ol.geom).
I was able to draw a polygon on canvas:
var geoJson = '{"type":"Polygon","coordinates":[[[32.00592041015625,49.55951603052614],[31.97296142578125,49.51673910294474],[32.103424072265625,49.433752230525585],[32.224273681640625,49.346151509388676],[32.54974365234375,49.24718981286537],[32.81890869140625,49.09814978542761],[32.80517578125,49.0729662700941],[32.85736083984375,49.0657686340536],[32.87933349609375,49.08376076915357],[32.95623779296875,49.067568140816434],[32.98370361328125,49.09095579858044],[33.145751953125,49.081961848889364],[33.11828613281251,49.067568140816434],[33.123779296875,49.056770122686174],[33.24737548828125,49.063969062121345],[33.23089599609375,49.16284875720291],[33.12652587890625,49.18080571099239],[33.079833984375,49.256153800301064],[32.95898437500001,49.28841067865025],[32.87933349609375,49.3295971091282],[32.83538818359375,49.38863055043896],[32.8436279296875,49.42794681507826],[32.67608642578125,49.4672315972079],[32.67333984375001,49.4297331699307],[32.7447509765625,49.352413884497594],[32.66510009765625,49.34794084076262],[32.52227783203125,49.38460779401288],[32.31079101562501,49.513172668717914],[32.18856811523438,49.50247180563116],[32.18856811523438,49.50247180563116],[32.00592041015625,49.55951603052614]]]}';
var parser = new ol.format.GeoJSON();
var feature = parser.readFeature( geoJson );
var geom = feature.getGeometry();
var canvas = document.getElementById( 'canvas' );
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
})
});
function render( height, width, canvas, geometry, style ) {
var vectorContext = ol.render.toContext(
canvas.getContext( '2d' ),
{ size: [width, height] }
);
var geom = geometry.clone(),
line = geom.getCoordinates()[0],
extent = ol.extent.boundingExtent( line );
var dxy = ol.extent.getCenter(extent),
sxy = [
width / ol.extent.getWidth(extent),
height / ol.extent.getHeight(extent)
];
var dx = dxy[0],
dy = dxy[1],
sx = sxy[0],
sy = sxy[1];
geom.translate( -dx, -dy );
geom.scale( Math.min(sx, sy), -Math.min(sx, sy) );
geom.translate( width / 2, height / 2 );
vectorContext.setStyle( style );
vectorContext.drawGeometry( geom );
}
geom.transform( 'EPSG:4326', 'EPSG:3857' );
render( 400, 400, canvas, geom, style );
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
<canvas id="canvas" width="400" height="400" style="width: 400px; height: 400px;"></canvas>
Example:
OpenLayers rendering Geometry to Canvas
I was recently tasked with creating the map for my Wurm Online game alliance. I crafted a genius SVG-based overlay over a static image of an in-game map. Basically it takes data from a spreadsheet and renders Villages as colored circles on the map.
However, we have members all the over the map, so went about to seeing how I could create a zoom-able web-based map of our lands. The game admins give us a map dump every year or thereabouts, so we can create custom map applications however we feel. I downloaded the recent map dump for the island/server I care about, Xanadu.
The Xanadu dump is a 62MB PNG with a resolution of 8192 x 8192 pixels. I found a tile making program (MapTiler version 7), and I went about creating tiles. After the tiles are done rendering, the program itself creates HTML files with embedded JavaScript all programatically. It gave me a head start with OpenLayers3.
I was able to re-calculate Village coordinates and cobble together a zoom-able tiled map with Village circles. Needless to say, I was very happy when I got my custom OpenLayers3 map. (Working example: http://jackswurmtools.com/Content/Static/map.html)
The way I got it set up, each map "decoration" or colored circle is its own Vector.
The chief complaint from my fellow gamers about my zoom-able map, is that the color Village circles are too big zoomed out, yet too small when zoomed in.
I've tried all kinds of things, but I have yet to find the right examples. I'm used to finding and transforming SVG elements based on events, but the OP3 canvas rendering is NOT obvious to me in the DOM.
Some of my questions are:
How can I detect when my map has been zoomed? Is there some callback I'm missing?
And when a zoom is detected, how can I iterate through all my vectors and update a circle radius.
// jacks fully zoomable xanadu map
var data =
[{
X: "6744",
Y: "-2355.75",
Name: "Amish Creek",
Villagers: ["Aniceset", "Fulano"],
BackColor: "Aquamarine",
LandMarkType: "Member"
}, {
X: "6808.75",
Y: "-2265.125",
Name: "Amish Estates",
Villagers: ["Aniceset", "Villagers"],
BackColor: "Purple",
LandMarkType: "Member"
}];
console.log(data);
var mapExtent = [0.00000000, -8192.00000000, 8192.00000000, 0.00000000];
var mapMinZoom = 0;
var mapMaxZoom = 5;
var mapMaxResolution = 1.00000000;
var tileExtent = [0.00000000, -8192.00000000, 8192.00000000, 0.00000000];
var mapResolutions = [];
for (var z = 0; z <= mapMaxZoom; z++) {
mapResolutions.push(Math.pow(2, mapMaxZoom - z) * mapMaxResolution);
}
var mapTileGrid = new ol.tilegrid.TileGrid({
extent: tileExtent,
minZoom: mapMinZoom,
resolutions: mapResolutions
});
var features = [];
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'PNGMAP',
tileGrid: mapTileGrid,
url: "http://jackswurmtools.com/Content/Static/{z}/{x}/{y}.png"
})
}),
],
view: new ol.View({
zoom: 4,
center: [6602.375, -2250.3125],
projection: ol.proj.get('PNGMap'),
maxResolution: mapTileGrid.getResolution(mapMinZoom)
}),
});
map.getView();
map.on('singleclick', function(evt) {
var coord = evt.coordinate;
console.log(coord);
$("#coord-overlay").html("[" + coord[0] + ", " + coord[1] + "]");
});
// zoom stuff?
// add layers via JSON iteration
renderSVG(data);
drawLines();
function renderSVG(data) {
var vectorSource = new ol.layer.Vector({});
console.log(map.getView().getZoom());
jQuery.each(data, function() {
var fill = new ol.style.Fill({
color: this.BackColor
});
var stroke = new ol.style.Stroke({
color: [180, 0, 0, 1],
width: 1
});
var style = new ol.style.Style({
image: new ol.style.Circle({
fill: fill,
stroke: stroke,
radius: map.getView().getZoom() * 5,
opacity: 0.7
}),
fill: fill,
stroke: stroke,
text: new ol.style.Text({
font: '12px helvetica,sans-serif',
text: this.Name,
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
});
var point_feature = new ol.Feature({});
var point_geom = new ol.geom.Point([this.X, this.Y]);
point_feature.setGeometry(point_geom);
var vector_layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [point_feature],
})
});
vector_layer.setStyle(style);
map.addLayer(vector_layer);
});
}
function drawLines() {
var stroke = new ol.style.Stroke({
color: [255, 0, 0, 1],
width: 6
});
var style = new ol.style.Style({
fill: null,
stroke: stroke,
text: new ol.style.Text({
font: '12px helvetica,sans-serif',
text: "Sandokhan / Wargasm Canal",
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
});
var line_feature = new ol.Feature({});
var coords = [
[6607.5, -1921],
[6894, -1921]
];
var layerLines = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString(coords, 'XY'),
name: 'Line',
})]
})
});
layerLines.setStyle(style);
map.addLayer(layerLines);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.8.2/ol.min.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.8.2/ol.min.js" type="text/javascript"></script>
<div id="map"></div>
<div id="coord-overlay">[6612, -2252]</div>
<input id="slider" type="range" min="0" max="1" step="0.1" value="1" oninput="layer.setOpacity(this.value)">
You are looking for a resolution listener, the API docs is an excellent place:
map.getView().on('change:resolution', function(){
var zoom = map.getView().getZoom();
// your conditions
if (zoom < 10) {
// your ol.layer.Vector assuming `vector_layer` global variable
vector_layer.setStyle(style_with_another_radius);
}
});
you can listen to the moveend event for the zoom, however it is also fired when you move the map:
map.on('moveend', function(){
var radius= map.getView().getZoom() * someFactor; // or whatever +,/ ...
yourVectorVillage.setStyle(new ol.style.Circle({ radius : radius}));
// or a style of your own where you can modify the radius
});
Is it possible in OpenLayers 3 to create a text label which clones multiple times along a linestring feature, depending on a scale? Something like:
Here you can see, that when we change scale label "IX Corps Blvd" appears twice. How can we implement this?
You can achieve this with style function. My code sample is about making arrows to line string (slightly different case), but I have commented parts necessary to be changed (at least):
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector();
var styleFunction = function(feature) {
var geometry = feature.getGeometry();
var styles = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({ // apply street style here
color: '#ffcc33',
width: 2
})
})
];
geometry.forEachSegment(function(start, end) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);
// arrows
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(end),
image: new ol.style.Icon({ // Use here label, not icon.
src: 'http://openlayers.org/en/v3.17.1/examples/data/arrow.png',
anchor: [0.75, 0.5],
rotateWithView: false,
rotation: -rotation
})
}));
});
return styles;
};
var vector = new ol.layer.Vector({
source: source,
style: styleFunction
});
map.addInteraction(new ol.interaction.Draw({
source: source,
type: /** #type {ol.geom.GeometryType} */ ('LineString')
}));
Some more effort is needed to place titles in correct placements. I left this answer like this to serve a solid starting point for building your feature.
My source:
[1] http://openlayers.org/en/master/examples/line-arrows.html
I was planning to draw polygon from lat long values referring this code.
open layers 3 how to draw a polygon programmically?
var polyCoordinates =[[1.300910900488229, 44.28372648003116],[1.3373031124022878, 44.13311552125895],[1.6648330196289067, 44.12030076099872]];
var polygon = new OpenLayers.Geometry.Polygon([polyCoordinates]);
// Create feature with polygon.
var feature = new OpenLayers.Feature(polygon);
// Create vector source and the feature to it.
var vectorSource = new OpenLayers.source.Vector();
// Create the vectorial layer
var vectorLayer = new OpenLayers.Layer.Vector('Vector Layer', {
source: vectorSource
styleMap: new OpenLayers.StyleMap({
'default': OpenLayers.Util.applyDefaults({
strokeWidth: 3,
graphicName: 'triangle',
pointRadius: '${radius}',
rotation: '${angle}'
}, OpenLayers.Feature.Vector.style['default']
),
'select': OpenLayers.Util.applyDefaults({
pointRadius: '${radius}'
}, OpenLayers.Feature.Vector.style['select']
)
})
});
OpenLayers.source is undefined is showing as error. Any help would be appreciated.
var sitePoints = [];
var coordinates =[{"long":1.300910900488229,"lat":44.28372648003116},
{"long":1.3373031124022878,"lat":44.13311552125895},
{"long":1.6648330196289067,"lat":44.12030076099872}];
var siteStyle = {
label:'ring',
title: 'press to close as a ring',
cursor: "pointer",
fontSize: '8px',
fontColor: '#222',
pointRadius: 10,
fillColor: '#cccccc',
strokeColor: '#444444'
};
var epsg4326 = new OpenLayers.Projection("EPSG:4326");
for (var i in coordinates) {
var coord = coordinates[i];
var point = new OpenLayers.Geometry.Point(coord.long, coord.lat);
// transform from WGS 1984 to Spherical Mercator
point.transform(epsg4326, map.getProjectionObject());
sitePoints.push(point);
}
console.log(sitePoints);
var linearRing = new OpenLayers.Geometry.LinearRing(sitePoints);
var geometry = new OpenLayers.Geometry.Polygon([linearRing]);
var polygonFeature = new OpenLayers.Feature.Vector(geometry, null, siteStyle);
vectorLayer.addFeatures([polygonFeature]);
map.addLayer(vectorLayer);
Here is a proper way to do this in OpenLayers 3, which has a different API than previous versions.
var polyCoordinates =[
[1.300910900488229, 44.28372648003116],
[1.3373031124022878, 44.13311552125895],
[1.6648330196289067, 44.12030076099872]];
var polygon = new ol.geom.Polygon([polyCoordinates]);
polygon.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
// Create feature with polygon.
var feature = new ol.Feature({
geometry: polygon
});
// Create vector source and the feature to it.
var vectorSource = new ol.source.Vector({
features: [feature]
});
// Create the vectorial layer
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#eedd00',
width: 3
})
})
});
Edit: If you stick with OpenLayers 2, you need to create the polygon via linear ring. The setup is a little bit different. There is no OpenLayers source to deal with.
var polyCoordinates =[
[1.300910900488229, 44.28372648003116],
[1.3373031124022878, 44.13311552125895],
[1.6648330196289067, 44.12030076099872]];
// Create the polygon via linear ring
var points = [];
for (var i = 0; i < polyCoordinates.length; i++) {
coord = polyCoordinates[i];
points.push(new OpenLayers.Geometry.Point(coord[0], coord[1]));
}
var linearRing = new OpenLayers.Geometry.LinearRing(points);
var polygon = new OpenLayers.Geometry.Polygon([linearRing]);
var srcProj = new OpenLayers.Projection("EPSG:4326");
var targetProj = new OpenLayers.Projection("EPSG:3857");
polygon.transform(srcProj, targetProj);
// Create feature with polygon.
var feature = new OpenLayers.Feature.Vector(polygon);
// Create the vectorial layer
var vectorLayer = new OpenLayers.Layer.Vector('Vector Layer',
OpenLayers.Feature.Vector.style['default']
);
vectorLayer.addFeatures([feature]);
I've checked, similar questions have been asked, but have been left partially answered or not answered at all.
I need to build an eraser tool with PaperJS that will be able to erase existing paths, without erasing the image underneath.
So the image can reside on the first layer, and the paths on the second. See the accompanying JSFiddle: jsfiddle which shows two attempts:
paper.install(window);
var canvas = document.getElementById("myCanvas");
paper.setup(canvas);
//the yellow background (can also be background image) which should NOT be erased
var rect = new Rectangle(new Point(0, 0), new Point(paper.view.size.width, paper.view.size.height));
var rectPath = new Path.Rectangle(rect);
rectPath.fillColor = 'yellow';
//first attempt to erase the black line
var first = paper.project.activeLayer;
var second = new Layer();
var from = new Point(50, 0);
var to = new Point(50, 100);
var path1 = new Path.Line(from, to);
path1.strokeColor = 'black';
path1.strokeWidth = 40;
var from = new Point(0, 50);
var to = new Point(100, 50);
var path2 = new Path.Line(from, to);
path2.strokeColor = 'green'; //I've tried other colors as well, this seems irrelevant
path2.strokeWidth = 40;
path2.blendMode = 'destination-out';
//So I saw this
var path = new CompoundPath({
children: [
new Path.Circle({
center: new Point(200, 50),
radius: 30
}),
new Path.Circle({
center: new Point(200, 50),
radius: 10
})
],
fillColor: 'black',
selected: true
});
//second attempt
//I need to actually erase with one line through lots of paths, not sure how to implement it with this
var path = new CompoundPath({
children: [
new Path.Line({
from: [350, 0],
to: [350, 100],
strokeWidth: 30,
strokeColor: 'green' //irrelevant it seems
}),
new Path.Line({
from: [300, 50],
to: [400, 50],
strokeWidth: 30,
strokeColor: 'white' //irrelevant it seems
})
],
strokeColor: 'black',
selected: true,
strokeWidth: 20
});
paper.view.draw();
<script src="http://tmantechblog.com/testpaperjs/js/libs/paper.js"></script>
<canvas id="myCanvas" height='500' width='500'>This does not support HTML5 canvas</canvas>
The first attempt tries to use blendMode='destination-out' but it leaves a white mark rather than a transparent path
The second implementation tries to mimic the compoundPath example provided there, but where the paths cross, no hole is produced. Also, I'm unsure how this can be used to implement an eraser across multiple paths.
Any advice on how to proceed will be appreciated. Otherwise I'll have to port my whole project either to the basic HTML 5 canvas or FabricJS, or something similar.