I have a circle, which has an animation running on it, here is a quick hacked jsFiddle to demonstrate.
http://jsfiddle.net/qpLza4a0/
I can not seem to get the zIndex property working on the circle (not the circle animation), it appears that the animation is on top of the circle.
Where should I put the zIndex property to get the circle on top?
The animation always runs after the placement of the marker regardless of the zIndex. So you will need to draw the marker after the animation. I stored the marker style so the event-handler can use it.
var mstyle=new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: "#fff"
}),
stroke: new ol.style.Stroke({
color: "blue",
width: 2
}),
}),
zIndex: 100
});
marker.setStyle(mstyle);
And changed the postcompose event-handler to draw the marker over/after the animation.
function pulsate(map, color, feature, duration) {
var start = new Date().getTime();
var key = map.on('postcompose', function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
var flashGeom = feature.getGeometry().clone();
var elapsed = frameState.time - start;
var elapsedRatio = elapsed / duration;
var radius = ol.easing.easeOut(elapsedRatio) * 35 + 5;
var opacity = ol.easing.easeOut(1 - elapsedRatio);
var fillOpacity = ol.easing.easeOut(0.5 - elapsedRatio)
vectorContext.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
snapToPixel: false,
fill: new ol.style.Fill({
color: 'rgba(119, 170, 203, ' + fillOpacity + ')',
}),
stroke: new ol.style.Stroke({
color: 'rgba(119, 170, 203, ' + opacity + ')',
width: 2 + opacity
})
})
}));
vectorContext.drawGeometry(flashGeom);
// Draw the marker (again)
vectorContext.setStyle(mstyle);
vectorContext.drawGeometry(feature.getGeometry());
if (elapsed > duration) {
ol.Observable.unByKey(key);
pulsate(map, color, feature, duration); // recursive function
}
map.render();
});
}
Two new lines:
vectorContext.setStyle(mstyle);
vectorContext.drawGeometry(feature.getGeometry());
set the undisturbed marker-style and redraw the feature geometry.
See this jsFiddle...
Related
I´m trying to draw an arc using mouse events with paper.js
The user must be able to draw an arc from 0 degree to 360 degree.
The issue that I´m facing is that I can draw 270 degree arc but more than 270, the arc flips to another quadrant.
Start point must be located anywhere
A sketch can be found here:
http://sketch.paperjs.org/#V/0.12.7/S/nVTBjpswEP2VEZeQXYcG2l6IOFTpZQ+RVruHHkpVeR1nQSE2MoZNFPHvtbHdeCGtorWEsOf5zTyex5wDhg80SIPnPZWkCFBA+FavOywAC/KbNHSVs5zptcDbsm2yZLlcmQChTFKRMfoGj7xkMvyyXCL1zC3eSCzkCP5qYJeTxJDBsAPLIlqXglQ0POcM1DDpU/tGJmhEpJDY9a6sqjWvuNo3e6kw2c9y1s9XoAvYD/AquNR6NFLwPXVcQbczNAZ/lFtZpBBPgDWuNYe3TLEADKzLAgyV4TJyJjmvIs42vG3ohndaz65lRJachbRTHzeHsyNpT2rPsgGPaj2PjshfnbSNjtLF2WD2wnjlI0lWT6OYvVY0C7skGmYP7EnZilmz6OJRxFXxuIJ0uMq0ueun7+GEgSZZ0bBE9hzNCb7Pa08qEvSgDAodaMNeh3wTJDQC9J5e2+a8BKcIV3WBYzS8kqu1TRfYhqKyFQy8xtgJfkj9gB5H14fREe5tF95ttCTCG1tyjt5zTn85pxGnKZnjXCi9R5eFaq7X4iYZcAcjIQoys2Rhq3xKbhHnMl3kXc30D8n8Q6bdj/J/xMRJjusKb7/xn/974+11t03Um7+Z+ne+CIr3w+1sgvTnr/4P
and this is the implemented code:
var arc_cse;
var radius=200;
var center=new Point(400,400);
var start=new Point(400,500);
var c1 = new Path.Circle({
center: center,
radius: 2,
fillColor: 'black'
});
arc_cse = new Path({
strokeColor: 'red',
strokeWidth: 1,
strokeCap: 'round',
});
tool.onMouseMove = function(event) {
var p=new Point(event.point.x,event.point.y);
var v1=start-center;
var v2=p-center;
var angle=(v2.angleInRadians-v1.angleInRadians);
var arcval=arc_CRD(v1.angleInRadians,v2.angleInRadians,angle,center,radius);
arc_cse.remove();
arc_cse= new Path.Arc(arcval);
}
function arc_CRD(alpha1,alpha2,angle,center,radius){
return {
from: {
x: center.x + radius*Math.cos(alpha1),
y: center.y + radius*Math.sin(alpha1)
},
through: {
x: center.x + radius * Math.cos(alpha1 + (alpha2-alpha1)/2),
y: center.y + radius * Math.sin(alpha1 + (alpha2-alpha1)/2)
},
to: {
x: center.x + radius*Math.cos(alpha1+(alpha2-alpha1)),
y: center.y + radius*Math.sin(alpha1+(alpha2-alpha1))
},
strokeColor: 'red',
strokeWidth: 3,
strokeCap: 'round'
}
}
Thanks in advance
There are certainly tons of ways to do this but here's how I would do it: sketch.
This should help you finding the proper solution to your own use case.
function dot(point, color) {
const item = new Path.Circle({ center: point, radius: 5, fillColor: color });
item.removeOnMove();
}
function drawArc(from, center, mousePoint) {
const radius = (from - center).length;
const circle = new Path.Circle(center, radius);
const to = circle.getNearestPoint(mousePoint);
const middle = (from + to) / 2;
const throughVector = (middle - center).normalize(radius);
const angle = (from - center).getDirectedAngle(to - center);
const through = angle <= 0
? center + throughVector
: center - throughVector;
const arc = new Path.Arc({
from,
through,
to,
strokeColor: 'red',
strokeWidth: 2
});
circle.removeOnMove();
arc.removeOnMove();
// Visual helpers
dot(from, 'orange');
dot(center, 'black');
dot(mousePoint, 'red');
dot(to, 'blue');
dot(middle, 'lime');
dot(through, 'purple');
circle.strokeColor = 'black';
return arc;
}
function onMouseMove(event) {
drawArc(view.center + 100, view.center, event.point);
}
Edit
In answer to your comment, here is a more mathematical approach: sketch.
This is based on your code and has exactly the same behavior so you should have no difficulty using it.
The key of both implementation is the Point.getDirectedAngle() method which allow you to adapt the behavior depending on the through point side.
const center = new Point(400, 400);
const start = new Point(400, 500);
const c1 = new Path.Circle({
center: center,
radius: 2,
fillColor: 'black'
});
let arc;
function getArcPoint(from, center, angle) {
return center + (from - center).rotate(angle);
}
function drawArc(from, center, mousePoint) {
const directedAngle = (from - center).getDirectedAngle(mousePoint - center);
const counterClockwiseAngle = directedAngle < 0
? directedAngle
: directedAngle - 360;
const through = getArcPoint(from, center, counterClockwiseAngle / 2);
const to = getArcPoint(from, center, counterClockwiseAngle);
return new Path.Arc({
from,
through,
to,
strokeColor: 'red',
strokeWidth: 1,
strokeCap: 'round'
});
}
function onMouseMove(event) {
if (arc) {
arc.remove();
}
arc = drawArc(start, center, event.point);
}
In my app I wrote an ol.interaction.Draw code that allow me to draw a circle everytime I click on one map panel, and this circle work good for me because I can move, rotate and rescale proportionally it. This is my code:
map.addInteraction(new ol.interaction.Modify({
features: this.features,
deleteCondition: function (event) {
return ol.events.condition.shiftKeyOnly(event) && ol.events.condition.singleClick(event);
}
}));
this.draw = new ol.interaction.Draw({
features: this.features,
type: 'Circle',
draggable:true;
});
this.draw.on('drawstart', function () {
this.features.clear();
}, this);
this.map.addInteraction(this.draw);
But I would like to draw an image (e.g. with the source media/image/landscape.png), instead of one circle, but with the same features (drag and drop, rotate, rescale proportionally). How I could do it?
You would probably want to draw circles but style them using your png as an icon. Scaling would be based on the circle radius. Circle geometry doesn't include rotation but by using a geometryFunction in the interaction you could set a rotation and use that to rotate the icon (the angle needs to be adjusted depending on which edge or corner of the icon is used for the rotation).
var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;
styles = [
new ol.style.Style({
fill: new ol.style.Fill({
color: [255, 255, 255, 0.5]
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: white,
width: width + 2
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: blue,
width: width
})
}),
new ol.style.Style({
image: new ol.style.Circle({
radius: width * 2,
fill: new ol.style.Fill({
color: blue
}),
stroke: new ol.style.Stroke({
color: white,
width: width / 2
})
}),
zIndex: Infinity
})
];
var treeStyle = new ol.style.Style({
image: new ol.style.Icon({
src: 'https://www.freeiconspng.com/uploads/oak-tree-icon-png-17.png'
})
});
styleFunction = function(feature, resolution) {
if (feature.getGeometry().getCenter) {
treeStyle.setGeometry(new ol.geom.Point(feature.getGeometry().getCenter()));
treeStyle.getImage().setRotation(feature.getGeometry().get('rotation'));
treeStyle.getImage().setScale(feature.getGeometry().getRadius()/(150*resolution));
return treeStyle;
} else {
return styles;
}
}
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var vector = new ol.layer.Vector({
source: source,
style: styleFunction
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var draw = new ol.interaction.Draw({
source: source,
type: 'Circle',
geometryFunction: function(coordinates, geometry) {
var center = coordinates[0];
var last = coordinates[1];
var dx = center[0] - last[0];
var dy = center[1] - last[1];
var radius = Math.sqrt(dx * dx + dy * dy);
var rotation = Math.PI - Math.atan2(dy, dx);
geometry = geometry || new ol.geom.Circle(center, radius);
geometry.setCenter(center);
geometry.setRadius(radius);
geometry.set('rotation', rotation);
return new ol.geom.Circle(center, radius);
},
style: styleFunction
});
map.addInteraction(draw);
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
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
});
I am creating a circle as a group of kinetic arcs. When I cache the group and subsequently call the draw function on the layer, three quarters of the circle are hidden. I think layer.draw may require an offset but really I'm only guessing. When I remove the fill, stroke or opacity from the arc or the object literal from the cache call then the full circle is displayed. http://jsfiddle.net/leydar/gm2FT/5/ Any insights gratefully received.
function createArc(n){
var arc = new Kinetic.Arc({
innerRadius: 30,
outerRadius: 50,
/* if I remove the fill, stroke or opacity
the full wheel is correctly displayed */
fill: 'blue',
stroke: 'black',
opacity: 0.3,
strokeWidth: 1,
angle: 36,
rotation: 36*n
});
return arc;
}
function init() {
var arc;
var stage = new Kinetic.Stage({
container: 'container',
width: 104,
height: 104
});
var layer = new Kinetic.Layer();
var circle = new Kinetic.Group();
for(var i=0;i<10;i++) {
arc = createArc(i);
circle.add(arc);
};
layer.add(circle);
stage.add(layer);
/* if I do not cache or do not call layer.draw()
then again the wheel is correctly displayed */
circle.cache({
x: -52,
y: -52,
width: 104,
height: 104,
drawBorder: true
});
layer.draw();
}
init();
Stephen
This is a bug of KineticJS.
You may use this workaround:
Kinetic.Arc.prototype._useBufferCanvas = function() {
return false;
};
http://jsfiddle.net/gm2FT/6/
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var Circle = new Kinetic.Circle ({
x: 100,
y: 100,
radius: 10,
fill: 'green',
stroke: 'black',
strokeWidth: 5
});
layer.add(Circle);
stage.add(layer);
var a = 1;
var anim = new Kinetic.Animation(function(frame) {
Circle.setX(frame.time * 350 / 1000 + 100);
}, layer);
anim.start();
How do i stop the animation at a specific point or coordinate? like animate to x=700 and then stop. i want to have a circle that is able to animate with a button to coordinate x=700, stop and then stop, and after that with another button back or down.
thank you.
There are 2 ways,
1.
var anim = new Kinetic.Animation(function(frame) {
if(Circle.getX() < 700)
Circle.setX(frame.time * 350 / 1000 + 100);
else
this.stop();
}, layer);
OR2. Use Kinetic.Transition check here