Trigger mouseover event on a Raphael map - javascript

I am using the Raphael plugin for the first time and so far I managed to create a map of Germany and to outline all different regions inside. I found out how to bind mouse-over effects, so when I hover over a region its color changes. Everything looks fine until the moment when I want to trigger the same mouse-over effect from outside the map. There is a list of links to all the regions and each link should color its respective geographical position (path) on the map when hovered. The problem is that I don't know how to trigger the mouse-over effect from outside.
This is the reference guide I used for my code: Clickable France regions map
This is my map initialization:
var regions = [];
var style = {
fill: "#f2f2f2",
stroke: "#aaaaaa",
"stroke-width": 1,
"stroke-linejoin": "round",
cursor: "pointer",
class: "svgclass"
};
var animationSpeed = 500;
var hoverStyle = {
fill: "#dddddd"
}
var map = Raphael("svggroup", "100%", "auto");
map.setViewBox(0, 0, 585.5141, 792.66785, true);
// declaration of all regions (states)
....
var bayern = map.path("M266.49486,..,483.2201999999994Z");
bayern.attr(style).data({ 'href': '/bayern', 'id': 'bayern', 'name': 'Bayern' }).node.setAttribute('data-id', 'bayern');
regions.push(bayern);
This is where my "normal" mouse effects take place:
for (var regionName in regions) {
(function (region) {
region[0].addEventListener("mouseover", function () {
if (region.data('href')) {
region.animate(hoverStyle, animationSpeed);
}
}, true);
region[0].addEventListener("mouseout", function () {
if (region.data('href')) {
region.animate(style, animationSpeed);
}
}, true);
region[0].addEventListener("click", function () {
var url = region.data('href');
if (url){
location.href = url;
}
}, true);
})(regions[regionName]);
}
I have a menu with links and I want to bind each of them to the respective region, so that I can apply the animations, too.
$("ul.menu__navigation li a").on("mouseenter", function (e) {
// this function displays my pop-ups
showLandName($(this).data("id"));
// $(this).data("id") returns the correct ID of the region
});
I would appreciate any ideas! Thanks in advance!

I figured out a way to do it. It surely isn't the most optimal one, especially in terms of performance, but at least it gave me the desired output. I would still value a better answer, but as of right now a new loop inside the mouse-over event does the job.
$("ul.menu__navigation li a").on("mouseenter", function (e) {
// this function displays my pop-ups
showLandName($(this).data("id"));
// animate only the one hovered on the link list
var test = '/' + $(this).data("id");
for (var regionName in regions) {
(function (region) {
if (region.data('href') === test) {
region.animate(hoverStyle, animationSpeed);
}
})(regions[regionName]);
}
});

Related

How to Prevent Leaflet Sidebar from moving the map on the x-axis when it appears?

I am discovering Leaflet maps, and I decided to use a sidebar that appears when a marker is clicked, from this : https://github.com/Turbo87/leaflet-sidebar . As you can see on the video in the link, when you click the marker, the sidebar appears but also drags the map on the x axis, and I did not manage to find where I can prevent that. I would like to make it appear without moving the map.
Here is also the link of the example with the code : http://turbo87.github.io/leaflet-sidebar/examples/
I tried to add this, so it stays at the current coords when I click :
marker.on('click', function () {
var coord = e.latlng;
var lat = coord.lat;
var lng = coord.lng;
map.panTo([lat,lng]);
}
but it doesn't work, it only does if I set the coords before like this:
marker.on('click', function () {
map.panTo([47.392882, 0.683022]);
}
it can be done by changing the code in the L.Control.Sidebar file
show: function () {
if (!this.isVisible()) {
L.DomUtil.addClass(this._container, 'visible');
if (this.options.autoPan) {
this._map.panBy([-this.getOffset() / 2, 0], {
duration: 0.5
});
}
this.fire('show');
}
},
hide: function (e) {
if (this.isVisible()) {
L.DomUtil.removeClass(this._container, 'visible');
if (this.options.autoPan) {
this._map.panBy([this.getOffset() / 2, 0], {
duration: 0.5
});
}
this.fire('hide');
}
if(e) {
L.DomEvent.stopPropagation(e);
}
}
deleting this part
if (this.options.autoPan) {
this._map.panBy([this.getOffset() / 2, 0], {
duration: 0.5
});
}

How to create a Konva-React context menu

To the best of my knowledge there isn't an easy/built in way with Konva to create a context menu for right clicking on objects. I am busy working on a project which requires the use of context menus, so I thought I'd just create my own.
Needless to say I am fairly new to Konva, so I was hoping someone on SO might have more experience to help me get over the last hurdles.
I have create a sandbox, located HERE
The requirements are:
An object should be draggable. (I copied a working example off the Konva sandbox.)
An object should show a context menu when right clicked upon.
The context menu should be dynamic, thus allow for multiple items, each executing its own callback when clicked upon.
Once a selection has been made, the context menu should be closed.
Thus far I have gotten most of it right, but the things I am struggling with are:
I cannot figure out how to hover over one context menu item, have it highlighted, then move to the next which should be highlighted and the old one restored to original settings.
Moving out of the context menu repaints the whole object. I don't understand why.
Clicking on one items fires both item's callbacks. Why? I a targeting the specific menu item which was clicked on, but getting both?
This point is less of a bug and more that I am unsure as how to proceed: How would I prevent multiple context menus to be create if a user right clicks multiple times on the object? Conceptually I understand that I could search for any items in a layer(?) with the name of the context menu and close it, however I have no idea how to do this.
I would appreciate any help. Thanks in advance.
Not sure if I'm late but I would use React Portals, theres a example about it on the react-konva page: https://konvajs.github.io/docs/react/DOM_Portal.html
I forked your sandbox with how this would be done: https://codesandbox.io/s/km0n1x8367
Not in react but plain JS I am afraid, but it shines a light on some of what you will have to do.
Click the pink circle, then take option 2 and click sub-option 2.
Areas requiring more work:
deliver the menu config data via JSON
make adding callbacks a method within the class
add a timeout on the hide to allow shaky mouse hands
how to handle hiding sub-menus when user mouse-outs or clicks another option
add reveal & hide animations
// Set up the canvas / stage
var stage = new Konva.Stage({container: 'container1', width: 600, height: 300});
// Add a layer some sample shapes
var layer = new Konva.Layer({draggable: false});
stage.add(layer);
// draw some shapes.
var circle = new Konva.Circle({ x: 80, y: 80, radius: 30, fill: 'Magenta'});
layer.add(circle);
var rect = new Konva.Rect({ x: 80, y: 80, width: 60, height: 40, fill: 'Cyan'});
layer.add(rect);
stage.draw();
// that is the boring bit over - now menu fun
// I decided to set up a plain JS object to define my menu structure - could easily receive from async in JSON format. [Homework #1]
var menuData = { options: [
{key: 'opt1', text: 'Option 1', callBack: null},
{key: 'opt2', text: 'Option 2', callBack: null,
options: [
{key: 'opt2-1', text: 'Sub 1', callBack: null},
{key: 'opt2-2', text: 'Sub 2', callBack: null}
]
},
{key: 'opt3', text: 'Option 3', callBack: null},
{key: 'opt4', text: 'Option 4', callBack: null}
]};
// Define a menu 'class' object.
var menu = function(menuData) {
var optHeight = 20; // couple of dimension constants.
var optWidth = 100;
var colors = ['white','gold'];
this.options = {}; // prepare an associative list accessible by key - will put key into the shape as the name so we can can get from click event to this entry
this.menuGroup = new Konva.Group({}); // prepare a canvas group to hold the option rects for this level. Make it accessible externally by this-prefix
var _this = this; // put a ref for this-this to overcome this-confusion later.
// recursive func to add a menu level and assign its option components.
var addHost = function(menuData, hostGroup, level, pos){ // params are the data for the level, the parent group, the level counter, and an offset position counter
var menuHost = new Konva.Group({ visible: false}); // make a canvas group to contain new options
hostGroup.add(menuHost); // add to the parent group
// for every option at this level
for (var i = 0; i < menuData.options.length; i = i + 1 ){
var option = menuData.options[i]; // get the option into a var for readability
// Add a rect as the background for the visible option in the menu.
option.optionRect = new Konva.Rect({x: (level * optWidth), y: (pos + i) * optHeight, width: optWidth, height: optHeight, fill: colors[0], stroke: 'silver', name: option.key });
option.optionText = new Konva.Text({x: (level * optWidth), y: (pos + i) * optHeight, width: optWidth, height: optHeight, text: ' ' + option.text, listening: false, verticalAlign: 'middle'})
console.log(option.optionText.height())
option.optionRect
.on('mouseover', function(){
this.fill(colors[1])
layer.draw();
})
.on('mouseleave', function(){
this.fill(colors[0])
layer.draw();
})
// click event listener for the menu option
option.optionRect.on('click', function(e){
var key = this.name(); // get back the key we stashed in the rect so we can get the options object from the lookup list
if (_this.options[key] && (typeof _this.options[key].callback == 'function')){ // is we found an option and it has a real function as a callback then call it.
_this.options[key].callback();
}
else {
console.log('No callback for ' + key)
}
})
menuHost.add(option.optionRect); // better add the rect and text to the canvas or we will not see it
menuHost.add(option.optionText);
_this.options[option.key] = option; // stash the option in the lookup list for later retrieval in click handlers.
// pay attention Bond - if this menu level has a sub-level then we call into this function again.
if (option.options){
var optionGroup = addHost(option, menuHost, level + 1, i) // params 3 & 4 are menu depth and popout depth for positioning the rects.
// make an onclick listener to show the sub-options
option.callback = function(e){
optionGroup.visible(true);
layer.draw();
}
}
}
return menuHost; // return the konva group
}
// so - now we can call out addHost function for the top level of the menu and it will recurse as needed down the sub-options.
var mainGroup = addHost(menuData, this.menuGroup, 0, 0);
// lets be nice and make a show() method that takes a position x,y too.
this.show = function(location){
location.x = location.x - 10; // little offset to get the group under the mouse
location.y = location.y - 10;
mainGroup.position(location);
mainGroup.show(); // notice we do not draw the layer here - leave that to the caller to avoid too much redraw.
}
// and if we have a show we better have a hide.
this.hide = function(){
mainGroup.hide();
}
// and a top-level group listener for mouse-out to hide the menu. You might want to put a timer on this [Homework #3]
mainGroup.on('mouseleave', function(){
this.hide();
layer.draw();
})
// end of the menu class object.
return this;
}
// ok - now we can get our menu data turned into a menu
var theMenu = new menu(menuData);
layer.add(theMenu.menuGroup); // add the returned canvas group to the layer
layer.draw(); // and never forget to draw the layer when it is time!
//
// now we can add some arbitrary callbacks to some of the options.
//
// make a trivial function to pop a message when we click option 1
var helloFunc = function(){
alert('hello')
}
// make this the callback for opt1 - you can move this inside the menu class object as a setCallback(name, function()) method if you prefer [homework #2]
theMenu.options['opt1'].callback = helloFunc;
// put a function on sub2 just to show it works.
theMenu.options['opt2-2'].callback = function(){ alert('click on sub-2') };
// and the original reason for this - make it a context menu on a shape.
circle.on('click', function(e){
theMenu.show({x: e.evt.offsetX, y: e.evt.offsetY});
layer.draw();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.5.1/konva.min.js"></script>
<div id='container1' style="width: 300px, height: 200px; background-color: silver;"></div>

Animating jsplumb line

Is there any way to animate jsplumb connecting lines as they are being drawn? I want to have an animation, instead of just a line appearing.
I call jsPlumb.connect to draw the line upon clicking a div, like this
$("#manchester").on('click', function() {
jsPlumb.connect({source: "manchester", target: "paris"});
});
First we need to bind an event whenever a connection has been made in order to animate the newly created connection:
jsPlumb.bind("jsPlumbConnection", function(ci) {
new animateConn(ci.connection); //call the animate function for the newly created function
}
Now in the animation function just update the position of connection overlay to get the animation. Before doing make sure that you add overlay to your connections:
jsPlumb.connect({
source: "manchester", target: "paris",
overlays:[
"Arrow",
[ "Label", { location:0.45, id:"arrow" } ]
]
});
Now the animateConn function:
var interval = null;
animateConn = function(conn) {
var arrow = conn.getOverlay("arrow");
interval = window.setInterval(function() {
arrow.loc += 0.05;
if (arrow.loc > 1) {arrow.loc = 0;}
try{
conn.repaint(); // writing in try block since when connection is removed we need to terminate the function for that particular connection
}catch(e){stop();}
}, 100);
},
stop = function() {
window.clearInterval(interval);
};
To customise the overlay refer the API DOC.

How to I scale the Raphael map in Rob Flaherty's US map example?

I'm trying to implement this awesome map, but I can't figure out how to scale it. Changing the size of the container div or the height/width values just crops the underlying map. I think I need paper.scaleAll(.5) in here somewhere, but can't figure it out. Thanks!
<script>
window.onload = function () {
var R = Raphael("container", 1000, 900),
attr = {
"fill": "#d3d3d3",
"stroke": "#fff",
"stroke-opacity": "1",
"stroke-linejoin": "round",
"stroke-miterlimit": "4",
"stroke-width": "0.75",
"stroke-dasharray": "none"
},
usRaphael = {};
//Draw Map and store Raphael paths
for (var state in usMap) {
usRaphael[state] = R.path(usMap[state]).attr(attr);
}
//Do Work on Map
for (var state in usRaphael) {
usRaphael[state].color = Raphael.getColor();
(function (st, state) {
st[0].style.cursor = "pointer";
st[0].onmouseover = function () {
st.animate({fill: st.color}, 500);
st.toFront();
R.safari();
};
st[0].onmouseout = function () {
st.animate({fill: "#d3d3d3"}, 500);
st.toFront();
R.safari();
};
})(usRaphael[state], state);
}
};
</script>
The other answer is almost correct, but you have to set the anchor point of the scale command to 0,0 so that each state is scaled from the same point:
element.transform("s2,2 0,0");
While you're at it, I'd make an R.set() element and add each state to it, so that you can apply the scale just to the states in the event that you add other objects, like a legend, that you do not want to scale:
usRaphael = {},
states = R.set();
//Draw Map and store Raphael paths
for (var state in usMap) {
usRaphael[state] = R.path(usMap[state]).attr(attr);
states.push(usRaphael[state]);
}
Then at the end:
states.transform("s2,2 0,0");
jsFiddle
After you draw the map (outside of your for loops) try the following:
R.forEach(function(element) {
element.transform("s2");
});
I'm not sure what version of Raphael you are using, but my code is assuming the latest. What this does is it iterates over every path on the paper and sets the transform to "scale 2". This will scale all of the paths by 2.

Calling js functions at same time yui

currently this is causing the (image) fadeout function to end, and then the fade in function fires. i need the images to crossfade and the opacity of each image to overlap. im having trouble getting this work. thoughts?
_initFade: function () {
this._timer = Y.later(this._intervalDuration, this, this._startPeriod, [], false);
},
_startPeriod: function () {
this._timer = Y.later(this._intervalDuration, this, this._fadeOut, [], true);
this._fadeOut();
},
_fadeOut: function(){
var host = this.get('host');
this._animOut.set('node', host._getCurrentBlock());
this._animOut.once('end', this._fadeIn, this);
this._animOut.run();
},
_fadeIn: function(){
var host = this.get('host'),
blocks = host.get('blocks'),
index = host.get('index');
index = host._moveIndex(host._getNextIndex());
var nextBlock = blocks.item(index);
this._transparent(nextBlock);
host.syncUI();
this._animIn.set('node', nextBlock);
this._animIn.run();
},
YUI doesn't support multiple animations which run in sync. But have a look at the 'tween' event of Y.Anim. It is called for every frame of the animation. So you can fade one image using the animation and adjust the opacity of the second image during the tween event.
For example, I use the tween event to animate multiple items simultaneously:
var someNode = Y.Node.create("<div></div>"); // invisible div to animate
Y.one(document.body).appendChild(someNode);
var anim = new Y.Anim({
node: someNode,
duration: 0.25,
from: { color: 'red' },
to: { color: 'white' }
});
anim.on('tween', function(event){
Y.StyleSheet().set('input.text.error', { backgroundColor: someNode.getStyle('color') });
// other animations
});

Categories

Resources