hammer.js, prevent "tap" from firing on "doubletap" - hammer.js

I have the following setup
function hammerIt(elm) {
hammertime = new Hammer(elm, {});
hammertime.on('tap doubletap pan pinch panstart panend pinchend swipe swipeleft swiperight swipedown swipeup', function(ev) {
// Doesn't work...
var doubletap = hammertime.get('doubletap');
var tap = hammertime.get('tap');
doubletap.recognizeWith(tap);
tap.requireFailure(doubletap);
if (ev.type == 'tap') {
doSomething();
}
if (ev.type == 'doubletap') { // This is never fired....
doSomethingElse();
}
// etc.
}
When I doubletap/-click on the element, both the tap and the doubletap event are fired. I only want the doubletap to fire but somehow my code doesn't work? Is it because I'm using on(events) and .get("event name") instead of dedicated events like in the example on https://hammerjs.github.io/require-failure/ or am I missing something else?

Thank you john Smith, based on your fiddle I've come up with a working solution:
function hammerIt(elm) {
hammertime = new Hammer.Manager(elm);
var doubletap = new Hammer.Tap({event: 'doubletap', taps: 2});
var tap = new Hammer.Tap({event: 'tap'});
var pan = new Hammer.Pan();
var pinch = new Hammer.Pinch({enable:true});
var swipe = new Hammer.Swipe();
hammertime.add([doubletap, tap, pan, pinch, swipe]);
hammertime.get('tap').requireFailure('doubletap');
hammertime.on('tap doubletap pan pinch panstart panend pinchend swipe swipeleft swiperight swipedown swipeup', function(ev) {
if (ev.type == 'tap') {
doSomething();
}
if (ev.type == 'doubletap') {
doSomethingElse();
}
// etc.
}
}
I think the problem was using "new Hammer(elem..." instead of a "new Hammer.Manager(elem)". This way I have to add the recognizers manually instead of using the default set but at least it works as expected :-)

Related

ZXing.Mobile - How to change the size of the camera scanner?

UPDATE:
I've tried implementing this in an App.cs method called OpenCameraScanner (you would call this on click of a button on the page from which you want to scan):
App.cs
------------------------------------------------
public static ZXingScannerPage ScanPage;
public static ZXing.Result ScanResult;
public static async void OpenCameraScanner()
{
ScanPage = new ZXingScannerPage(customOverlay: customOverlay);
ScanPage.OnScanResult += (result) =>
{
ScanPage.IsScanning = false;
ScanResult = result;
Device.BeginInvokeOnMainThread(() =>
{
App.CurrentApp.CurrentPage.Navigation.PopModalAsync();
App.CurrentApp.CurrentPage.DisplayAlert("Scanned Barcode", result.Text, "OK");
});
};
var scanPage = new NavigationPage(ScanPage);
await App.CurrentApp.CurrentPage.Navigation.PushModalAsync(ScanPage);
}
However, when this method is called, the screen that opens is blank white, and you can't see the camera view behind it. Not sure why?
I'm using ZXing.Mobile in a Xamarin.Forms project (for iOS right now) for camera scanning functionality on an iPad.
Currently, I have it working great with the following 2 lines:
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();
However, when the camera is open to scan, it takes up the entire iPad screen, which is really big.
Question: Is there a way to adjust the size of the camera overlay? (so that it's not full screen)
I see that the scanner.Scan() method takes an optional options parameter of type ZXing.Mobile.MobileBarcodeScanningOptions - I tried playing around with that, but the only possible relevant option there is a CameraResolutionSelector - but I'm having a really hard time finding any documentation on that.
There is a ZXing sample app that shows how to embed the ZXingScannerView and ZXingDefaultOverlay into a Xamarin.Form's Grid:
https://github.com/Redth/ZXing.Net.Mobile/blob/master/Samples/Forms/Core/CustomScanPage.cs
public CustomScanPage () : base ()
{
zxing = new ZXingScannerView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
AutomationId = "zxingScannerView",
};
zxing.OnScanResult += (result) =>
Device.BeginInvokeOnMainThread (async () => {
// Stop analysis until we navigate away so we don't keep reading barcodes
zxing.IsAnalyzing = false;
// Show an alert
await DisplayAlert ("Scanned Barcode", result.Text, "OK");
// Navigate away
await Navigation.PopAsync ();
});
overlay = new ZXingDefaultOverlay
{
TopText = "Hold your phone up to the barcode",
BottomText = "Scanning will happen automatically",
ShowFlashButton = zxing.HasTorch,
AutomationId = "zxingDefaultOverlay",
};
overlay.FlashButtonClicked += (sender, e) => {
zxing.IsTorchOn = !zxing.IsTorchOn;
};
var grid = new Grid
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
grid.Children.Add(zxing);
grid.Children.Add(overlay);
// The root page of your application
Content = grid;
}

Why does live camera capture control with Xamarin Forms on iOS freeze?

I downloaded the source for Xamarin Moments from GitHub and now I'm trying to convert the CameraPage renderer from Page to a ContentView
Then I refactored the code to make it a ContentView renderer. Most of the actual setup of the live preview and image capture comes from the Moments app with some refactoring where needed/preferred.
The live preview shows up but when I press the button to take the picture the app freezes without an exception, not even in Xcode's console view.
//this is how it's called:
btnTakePicture.Clicked += (s,e)=> { GetCameraImage().Wait(); };
// this method freezes
public async Task<byte[]> GetCameraImage()
{
byte[] imageBuffer = null;
if (captureDeviceInput != null)
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
Console.WriteLine("[HASFIQWRPPOA] This message shows up");
// this is where the app freezes, even though the live preview still moves.
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
Console.WriteLine("[CLKJFADSFQXW] THIS DOESN'T SHOW UP");
// var jpegImageAsBytes = AVCaptureStillImageOutput.JpegStillToNSData (sampleBuffer).ToArray ();
var jpegImageAsNsData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
Console.WriteLine("[ROIAJDGNQWTG]");
// var image = new UIImage (jpegImageAsNsData);
// var image2 = new UIImage (image.CGImage, image.CurrentScale, UIImageOrientation.UpMirrored);
// var data = image2.AsJPEG ().ToArray ();
imageBuffer = jpegImageAsNsData.ToArray();
Console.WriteLine("[FIOUJGAIDGUQ] Image buffer: "+imageBuffer.Length);
}
if (imageBuffer != null && imageBuffer.Length > 100)
{
using (var ms = new MemoryStream(imageBuffer))
{
var uiimg = UIImage.LoadFromData(NSData.FromStream(ms));
this.Add(new UIImageView(uiimg));
}
}
return imageBuffer;
}
Here is how I set the live preview
// This method runs fine and the camera preview is started as expected
public void SetupLiveCameraStream()
{
try
{
// add a UIView to the renderer
liveCameraStream = new UIView()
{
Frame = new CGRect(0f, 0f, Element.Width, Element.Height),
};
this.Add(liveCameraStream);
// find a camera
var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
if (captureDevice != null)
{
Console.WriteLine("[ZKSDJGWEHSY] Capture device found"); // not the case on simulator
captureSession = new AVCaptureSession();
videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
{
Frame = liveCameraStream.Bounds
};
liveCameraStream.Layer.AddSublayer(videoPreviewLayer);
ConfigureCameraForDevice(captureDevice);
captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
captureSession.AddInput(captureDeviceInput);
captureSession.AddOutput(stillImageOutput);
captureSession.StartRunning();
Console.WriteLine("[OIGAJGUWRJHWY] Camera session started");
}
else
{
Console.WriteLine("[OASDFUJGOR] Could not find a camera device");
}
}
catch (Exception x)
{
Console.WriteLine("[QWKRIFQEAHJF] ERROR:" + x);
}
}
I had this issue, and it turned out I was deadlocking because of a combination of using async/await with Task.Result. At a guess you could be experiencing something similar with your usage of Task.Wait().
The two sections of code:
btnTakePicture.Clicked += await (s,e) => { GetCameraImage().Wait(); };
And:
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);

Tracking frames and/or time during an animation

Can I call a function(one that will make another object visible/invisible) on a specific animation frame or time? I would like to have arrows describe the movement of the animation at certain times during the animation. While I can just make them visible when I start the animation and make them invisible when the animation stops, I would like to specify ranges inside the animation to do this
playPatientAnim: function (anim, callback) {
var pending = 1;
var me = this;
var finish = callback ? function () {
if (pending && !--pending) {
callback.call(me, anim);
}
} : null;
me.currentPatient.skinned.forEach(function (mesh) {
mesh.animations.forEach(function(anim){
anim.stop();
});
});
me.currentPatient.skinned.forEach(function (mesh) {
var animation = mesh.animations[anim];
animation.stop();
if (animation) {
pending++;
animation.onComplete = finish;
animation.play();
}
});
if (finish) {
finish();
}
}
You can make a mesh visible or invisible ( mesh.visible = false; //or true ). To change visibility at certain time you could use timestamp:
new Date().getTime() and calculate how you want to do the sequence of your animation.

Famo.us - triggering event and piping

Let's say I have three Views. AppView, MenuView and StripView. MenuView contains multiple StripViews and AppView contains one MenuView. How can I trigger event from StripView and listen on that event on AppView.
EDIT
Let's say I want to click on ImageSurface on StripView and reigster that event on AppView, and then do some transitionig.
MY SOLUTION
Everything is based on Timbre app, created in Famou.us Starter Kit Reference Tutorials
// StripView.js (_setListeners() is called in StripView constructor and bodySurface is defined in code)
function _setListeners() {
var eventScope = this._eventOutput;
this.backgroundSurface.on('click',function(){
eventScope.emit('test', { somedata:'some value'} );
}.bind(this));
}
// MenuView.js (_createStripViews() is called in MenuView constructor)
function _createStripViews() {
this.stripModifiers = [];
var yOffset = this.options.topOffset;
for (var i = 0; i < this.options.stripData.length; i++) {
var stripView = new StripView({
iconUrl: this.options.stripData[i].iconUrl,
title: this.options.stripData[i].title
});
var stripModifier = new StateModifier({
transform: Transform.translate(0, yOffset, 0)
});
this.stripModifiers.push(stripModifier);
this.add(stripModifier).add(stripView);
yOffset += this.options.stripOffset;
stripView.pipe(this._eventOutput);
}
}
//AppView.js (menuView is defined in code and _setListeners() is called in AppView constructor)
function _setListeners() {
this.menuView.on('test',function(){
console.log("IT WORKS");
}.bind(this));
}
You want to use Views built in handlers to achieve this. These are _eventInput and _eventOutput.. Here is an example using an ImageSurface in StripView and responding to a click in AppView..
Hope it helps!
// In StripView.js
var imageSurface = new ImageSurface();
imageSurface.on('click',function(){
this._eventOutput.trigger('image-click', { somedata:'some value'} );
}.bind(this));
// In AppView.js
var stripView = new StripView();
this.subscribe(stripView);
this._eventInput.on('image-click',function(data){
// Do Something
});

I want to combine the FormCode and AutomaticAdvance rotator types

How can I create a rotator with "FormCode" mode while being able to start that rotator automatically when the page loads? In other words, to start the rotator automatically while enabling end user to stop/start/move next/move back.
I need a complete sample code for the call.
I've used the following JavaScript/JQuery code for FormCode management:
<script type ="text/javascript">
//
function
startRotator(clickedButton, rotator, direction)
{
if
(!rotator.autoIntervalID)
{
refreshButtonsState(clickedButton, rotator);
rotator.autoIntervalID = window.setInterval(
function
()
{
rotator.showNext(direction);
}, rotator.get_frameDuration());
}
}
function
stopRotator(clickedButton, rotator)
{
if
(rotator.autoIntervalID)
{
refreshButtonsState(clickedButton, rotator)
window.clearInterval(rotator.autoIntervalID);
rotator.autoIntervalID =
null
}
}
function
showNextItem(clickedButton, rotator, direction)
{
rotator.showNext(direction);
refreshButtonsState(clickedButton, rotator);
}
// Refreshes the Stop and Start buttons
function
refreshButtonsState(clickedButton, rotator)
{
var
jQueryObject = $telerik.$;
var className = jQueryObject(clickedButton).attr("class"
);
switch
(className)
{
case "start"
:
{
// Start button is clicked
jQueryObject(clickedButton).removeClass();
jQueryObject(clickedButton).addClass(
"startSelected"
);
// Find the stop button. stopButton is a jQuery object
var stopButton = findSiblingButtonByClassName(clickedButton, "stopSelected"
);
if
(stopButton)
{
// Changes the image of the stop button
stopButton.removeClass();
stopButton.addClass(
"stop"
);
}
}
break
;
case "stop"
:
{
// Stop button is clicked
jQueryObject(clickedButton).removeClass();
jQueryObject(clickedButton).addClass(
"stopSelected"
);
// Find the start button. startButton is a jQuery object
var startButton = findSiblingButtonByClassName(clickedButton, "startSelected"
);
if
(startButton)
{
// Changes the image of the start button
startButton.removeClass();
startButton.addClass(
"start"
);
}
}
break
;
}
}
// Finds a button by its className. Returns a jQuery object
function
findSiblingButtonByClassName(buttonInstance, className)
{
var
jQuery = $telerik.$;
var ulElement = jQuery(buttonInstance).parent().parent();
// get the UL element
var allLiElements = jQuery("li", ulElement);
// jQuery selector to find all LI elements
for (var
i = 0; i < allLiElements.length; i++)
{
var
currentLi = allLiElements[i];
var currentAnchor = jQuery("A:first", currentLi);
// Find the Anchor tag
if
(currentAnchor.hasClass(className))
{
return
currentAnchor;
}
}
}
//]]>
And the following code for the calls:
<
a href="#" onclick="stopRotator(this, $find('<%= MyRotator.ClientID %>
')); return false;"
class="stopSelected" title="Stop">Stop
'), Telerik.Web.UI.RotatorScrollDirection.Left); return false;"
class="start" title="Start">Start
However, I cannot start the rotator on the page load. Tried to use this code in the in the MyRotator_DataBoud event, but did not work either:
protected void rrMyRotator_DataBound(object sender, EventArgs
e)
{
Page.RegisterClientScriptBlock(
"MyScript", " startRotator(this, $find('<%= MyRotator.ClientID %>'), Telerik.Web.UI.RotatorScrollDirection.Left);"
);
}
There are a couple of examples available in the Telerik online demos for this functionality and they have code you can use. See http://demos.telerik.com/aspnet-ajax/rotator/examples/clientapicontrol/defaultcs.aspx and http://demos.telerik.com/aspnet-ajax/button/examples/slideshow/defaultcs.aspx

Resources