In OpenLayer 3 I create a Draw interaction using the 'draw-feature' sample code they have on their website.
The only difference is that I supply my own condition function to the Draw constructor.
I would like to know if there is a way to determine within the condition function if the interaction/drawing has started?
Basically my goal is to change the behavior slightly so drawing a box is initiated with a CTRL-click rather than a click. But ending the drawing can be done with a simple click. So my approach would be something like this (in TypeScript)
var condition = (e: ol.MapBrowserEvent): boolean => {
return (myDraw.isStarted() ? true : e.originalEvent['ctrlKey']);
}
As far as I can see there's nothing like an isStarted() method in OL Draw class. If I had access to internal members I would resolve it by checking the length of myDraw.sketchCoords_ (haven't checked this but if 0 the drawing is not started yet). But I don't want to rely on private members, furthermore I'm using the minified version of OL where members names are transformed.
Try something like this:
var start_drawing = false;
function drawCondition(evt){
var ctrl = ol.events.condition.platformModifierKeyOnly(evt);
// this should be ol.events.condition.click
// but for some reason always returns false
var click = evt.type == 'pointerdown';
// to finish draw with click
if(start_drawing) return click;
// start drawing only with Ctrl + click
return ctrl && click;
}
// draw is a reference to ol.interaction.Draw
draw.on('drawstart', function(evt){
start_drawing = true;
});
draw.on('drawend', function(evt){
start_drawing = false;
});
Related
I have a project where I am using the vis.js timeline module as a type of image carousel where I have a start and an end time, plot the events on the timeline, and cycle through them automatically and show the image attached to each event in another container.
I already have this working and use something similar to the following to accomplish this, except one part:
var container = document.getElementById('visualization');
var data = [1,2,3,4,5];
var timeline = new vis.Timeline(container, data);
timeline.on('select', function (properties) {
// do some cool stuff
}
var i = 0;
(function timelapseEvents(i) {
setTimeout(function(){
timeline.setSelection(data[i], {focus: true, animation:true});
if (i < data.length - 1) {
timelapseEvents(i+1);
}
}, 2000);
})(i)
The timeline.setSelection() part above works, the timeline event is selected and focused on. However, the "select" event is NOT triggered. This is verified as working as expected in the documentation (under Events > timeline.select) where it says: Not fired when the method timeline.setSelection() is executed.
So my question is, does anyone know how to use the timeline.setSelection() method and actually trigger the select event? Seems unintuitive to me to invoke the timeline.setSelection()method and not actually trigger the select event.
Spent a few hours on this and came up short. I ended up just taking the code I had in my timeline.on('select', function (properties) { block and turning it into a function and calling it after the timeline.setSelection() call.
Basically, I didn't fix the issue but worked around it. Will keep an eye on this in case anyone actually is able to figure out how to add the select() event to the setSelection() method.
I'm developing a Chrome extension, and I'm adding an onmouseover handler to each of the images on a page. When the user mouses over an image, it's URL should be stored in a variable. I know I can easily get the value of the src attribute of the image, but I want the full URL. The src attribute stores the path of the image on the server. For example, when you right click an image in Google Chrome, you get the "Copy Image URL" option, which copies the image's URL to the clipboard.
Is there any way to achieve this? Thanks.
Instead of imageElement.getAttribute("src") or $("img.something").attr("src"), which reads the original markup, use imageElement.src property which will always give you the full URL.
var imgFullURL = document.querySelector('img.something').src;
or:
var imgFullURL = $('img.something')[0].src;
To extract host name, path name etc. - parse the url with URL() constructor, which works in modern browsers or use the legacy method via creating a temporary a node.
You can use window.location to get the page you are currently on and the following will give you the URL parts you need:
window.location.protocol = "http:"
window.location.host = "stackoverflow.com"
window.location.pathname = "/questions/32828681/how-to-get-url-of-an-image-in-javascript"
So, likely, you will need protocol, then "//", then host and finally the image src.
So the TL;DR is this:
(function() {
const imageInfo = new Object();
imageInfo.source = '';
window.addEventListener('mouseover', function (event) {
var currentElement = event.target;
// console.log(event.target);
if (currentElement.tagName === 'IMG') {
// console.log(currentElement.outerHTML + "is a photo");
imageInfo.source = currentElement.src;
// console.log("src is :" + imageInfo.source)
return imageInfo.source;
}
})
})();
See CodePen:
How to find the src URL for a photo by Trevor Rapp on
CodePen
This is how I thought about solving the problem in the most basic steps:
get the function to fire.
get the function to add an event listener that will perform an action on a mouseover event.
make that action know what the mouse is currently over.
figure out if what the mouse is currently over is an image or not.
create logic that will respond if it is.
that action that logic should do is return the source URL.
I will need to store that source URL if I am going to have to return it.
Here are how each of those solutions looked:
get the function to fire.
An IFFE is a great way to get a function to fire without having to worry about polluting the name space.
//skeleton for an IFFE statement
(function() {
})();
get the function to add an event listener that will perform an action on a mouseover event.
An event listener that could fire anywhere would have to be attached to the window or the document.
make that action know what the mouse is currently over.
This part will be combined with part 2. Event listener's first parameter is what type of event you want to listen for -- in this case 'mouseover. So now our code looks like this
(function () {
window.addEventListener('mouseover', function (event) {
//do stuff here
}
})()
figure out if what the mouse is currently over is an image or not.
*To figure out which element the mouse if currently over you would use Event.target.
The MDN definition for that is: *
The target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. --Event.Target
*So the code would then look like this: *
(function () {
window.addEventListener('mouseover', function (event) {
//get the current element the mouse is over
var currentElement = event.target;
}
})()
create logic that will respond if it is.
This was a little trickier since a photo or IMG can be presented in various ways.
I chose to create a solution for the simplest way, which is assuming that the web developer used the more syntactically correct version of an tag. However, there are many times when they may choose to apply a 'background-image' CSS property to a normal . Other things to consider could be the use of iframes, which can make detecting the attributes of child elements very frustrating since they don't allow bubbling to occur. To tell if an element is an , you can simply use elem.tagName === "IMG" for your logic check. While not included in the above code, if you wanted to check if a div is using the 'background-image', you could use something like element.getAttribute('style').includes('term') and switch out 'term' for something like 'url' or 'jpg' or 'png.' Kind of clunky and hacky, but just a thought. Anyway, the code would then become
(function () {
window.addEventListener('mouseover', function (event) {
//get the current element the mouse is over
var currentElement = event.target;
if (currentElement.tagName === 'IMG') {
//do stuff
}
}
})()
that action that logic should do is return the source URL.
Once you get the logic done and you have properly selected the element, then you can use element.src to get the source URL.
I will need to store that source URL if I am going to have to return it.
You can do this anyway you want, but I played around with instantiating an object since it sounded like the value would need to change often, but you didn't necessarily need to store previous values.
And so the final product could be something like this
(function() {
const imageInfo = new Object();
imageInfo.source = '';
window.addEventListener('mouseover', function (event) {
var currentElement = event.target;
// console.log(event.target);
if (currentElement.tagName === 'IMG') {
// console.log(currentElement.outerHTML + "is a photo");
imageInfo.source = currentElement.src;
// console.log("src is :" + imageInfo.source)
return imageInfo.source;
}
})
})();
I want to make a simple web page using bacon.js. It should have a button which toggles a boolean state by mouse click.
After setting up the streams, the app should be initialized by sending an object to an init stream. Here i just send the desired initial boolean state of the toggle (false).
The code looks like this (i faked the button clicks and initialization):
// Helper function
var neg = function (a) { return !a; };
// Fake of initialization stream. End after one element
var init = Bacon.sequentially(500, [false]);
// Fake of button click event stream.
var click = Bacon.repeatedly(1000, [{}]);
var toggle = init.concat(click).scan(null,
function(a, b) { return a === null ? b : neg(a); }).skip(1).toEventStream();
toggle.log();
// Output: false, true, false, true, ....
The above code (jsFiddle) works as expected, but i do not like that the toggle stream creation line is so complex.
If it would be possible to omit the seed value (take it from the stream) and if scan returns an EventStream instead of a Property, i could write:
var toggle = init.concat(click).scan(neg);
This could be read much nicer. Or if it would be possible to give the seed as stream i could just write:
var toggle = click.scan(init, neg);
Do you have any suggestions to make the code more clear?
Is there an alternative solution to using scan?
Should i make me an own scan method?
If you read what I wrote previously, ignore. it. :) This situation is exactly what flatMap is for: streams that create streams. Use flatMap.
// Helper function
var neg = function (a) { return !a; };
// Fake of initialization stream. End after one element
// Note the use of `later` instead of `sequentially`, by the way
var init = Bacon.later(500, false);
// Fake of button click event stream.
var click = Bacon.repeatedly(1000, [null]);
var toggle = init
.flatMap(function(initVal) { return click.scan(initVal, neg) });
toggle.log();
I am making a javascript canvas drawing program and I want the user to be able to choose between the pencil tool, circle tool and clearing screen on keypress.
In the following code the variable key_press holds the users selection. The whole program does not work when I don't assign anything to the variable, so I made the default value = pencil(). But now I cant use anything but pencil.
I post only relevant code here, but it is full in this jsfiddle
var canvas, context, tool, key_press;
// check for key press
window.addEventListener('keydown',function(event){
key_press= String.fromCharCode(event.keyCode);
},false);
function init () {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
//check user selection
if (key_press === "1") {
tool = new Pencil();
} else if (key_press === "2") {
tool = new Circle();
} else if (key_press === "3") {
canvas.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
tool = new Pencil();
} else tool = new Pencil(); //this part is probably causing the problem, but clear screen (selection 3) does not work either so it could be something different.
//onmouse calls and end of init()
}
//basically just two functions after init for the tools
function Pencil () {
//...
}
function Circle() {
//...
}
//calling main function init()
init();
Obviously the way I handle user input is bad. Could you point me in the right direction as to what I am doing wrong?
Your distance calculation wasn't working because you left off a , 2 in the second Math.pow call.
Your jsfiddle wasn't working because the default on a new fiddle is to run in window.load, but you then added another load event listener that never fired.
I've changed the code to reflect these changes (and make the context.arc call use the distance rather than z) and it appears to work:
http://jsfiddle.net/rWV5h/1/
I'm working on a responsive site with a specific set of jQuery functions for the desktop layout and mobile layout. They interfere with each other if they're both active at the same time.
By checking window.width, I'm able to deliver only the correct set of functions on page load, and I'd like to do the same on window.resize.
I've set up a stripped down Fiddle of where I'm at here: http://jsfiddle.net/b9XEj/
Two problems exist right now:
Either desktopFunctions or mobileFunctions will continuously fire on page resize, whether they have already been loaded or not.
If the window is resized beyond one breakpoint and then returned to the previous size, the incorrect set of functions will already have been loaded, interfering with the current set.
The window.resize function should behave in the following way:
Check if the correct set of functions currently active for the viewport size
If yes, return.
If no, fire correct set of functions and remove incorrect set of functions if they exist.
In the Fiddle example above, you would always see a single line, displaying either "Mobile Functions are active" or "Desktop Functions are active".
I'm a bit lost at this point, but I have tried using
if ($.isFunction(window.mobileFunctions))
to check if functions already exist, but I can't seem to get it working without breaking the overall function. Here's a fiddle for that code: http://jsfiddle.net/nA8TB/
Thinking ahead, this attempt also wouldn't take into account whether the incorrect set of functions exists already. So, I'm really hoping there's a way I can deal with this in a simpler way and solve both problems.
Any help would be much appreciated!
Following conquers 2 of the problems. The resize fires many times a second, so using a timeout will fix it firing your code constantly. It also adds a check to see if the same size is in effect, and return if it is
$(document).ready(function() {
var windowType;
var $wind = $(window);
var desktopFunctions = function() {
$('body').append('<p>Desktop functions are active</p>');
}
var mobileFunctions = function() {
$('body').append('<p>Mobile Functions are active</p>');
}
var mobileCheck = function() {
var window_w = $wind.width();
var currType = window_w < 940 ? 'mobile' :'desktop';
if (windowType == currType) {
$('body').append('<p>No Type Change, Width= '+window_w+'</p>');
return;
} else {
windowType = currType;
}
if (windowType == 'mobile') {
mobileFunctions();
} else {
desktopFunctions();
}
}
mobileCheck();
var resizeTimer;
$wind.resize(function() {
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(mobileCheck, 300)
});
});
DEMO: http://jsfiddle.net/b9XEj/1/
Without seeing some real world differences between your 2 sets of functions it is hard to provide gudance on how to stop them conflicting. One possibility is checking the windowType in your functions
You can prevent the continuous firing by adding a delay mobileCheck. Use a setTimeout along with a checkPending boolean value.
var checkPending = false;
$(window).resize(function(){
if (checkPending === false) {
checkPending = true;
setTimeout(mobileCheck, 1000);
}
});
See here: http://jsfiddle.net/2Q3pT/
Edit
As far as the second requirement, you could use this pattern to create or use the existing one:
mobileFunctions = mobileFunctions || function() {
// mobile functions active
};
See: http://jsfiddle.net/2Q3pT/2/