Kinetic.js don't lose grip on mouse out - html

When you drag an object and mouse is out of rendering area, dragging stops (firing an event) and user loses a grip.
It's extremelly inconvenient, taking into account that all other technologies (Flash, raw HTML5 Canvas, etc) allows to save the grip even if mouse is out.
Is there a way to solve the problem?
UPDATE: Up to the moment solved the problem by changing library file and binding listeners to the document, not to the container. I know that it's bad to hack into library files, but after inspecting the library's source code I haven't found out way around.

you could check if the element is out of sight and if so bring it back:
shape.on('dragend', function() {
var pos = shape.getPosition();
var layer = pos.getLayer();
if (pos.y < 0) {
pos.y = 0;
}
var maxY = layer.getHeight() - shape.getHeight();
if (pos.y > maxY) {
pos.y = maxY
}
shape.setPosition(pos);
}

Look at element.setCapture(). You can call it from within an event handler for a mouse event, eg. mousedown:
function mouseDown(e) {
e.target.setCapture();
e.target.addEventListener("mousemove", mouseMoved, false);
}
Although browser support is a bit spotty (IE and Firefox support it, not sure about other browsers), for cross browser use you would have to fall back to the binding on the document approach you've already hit upon.

Related

Animate CC HTML5 easelJS stage.X stage.Y mouse position not consistent between chrome and and firefox

I have an application where I need an information card to follow the position of the mouse.
I have used the following code:
stage.addEventListener("tick", fl_CustomMouseCursor.bind(this));
function fl_CustomMouseCursor() {
this.NameTag.x = stage.mouseX;
this.NameTag.y = stage.mouseY;
}
It works perfectly in Firefox but in Chrome and Safari the further away the mouse gets from 0,0 on the canvas the larger the distance between NameTag and the mouse (by a factor of 2).
I look forward to any comments.
I see the issue in Chrome as well as Firefox - I don't believe it is a browser issue.
The problem is that the stage itself is being scaled. This means that the coordinates are multiplied by that value. You can get around it by using globalToLocal on the stage coordinates, which brings them into the coordinate space of the exportRoot (this in your function). I answered a similar question here, which was caused by Animate's responsive layout support.
Here is a modified function:
function fl_CustomMouseCursor() {
var p = this.globalToLocal(stage.mouseX, stage.mouseY);
this.NameTag.x = p.x;
this.NameTag.y = p.y;
}
You can also clean up the code using the "stagemousemove" event (which is fired only on mouse move events on the stage), and the on() method, which can do function binding for you (among other things):
stage.on("stagemousemove", function(event) {
var p = this.globalToLocal(stage.mouseX, stage.mouseY);
this.NameTag.x = p.x;
this.NameTag.y = p.y;
}, this);
Cheers,

How to reset canvas context state entirely

I have a simple canvas animation, as follows:
function animate(){
var canvas = document.getElementById("canvas");
canvas.width = $(window).width();
canvas.addEventListener("click", replay, false);
var context = canvas.getContext("2d");
//animation code
function replay(e){
animate();
}
}
So my expectation is when the user clicks the canvas the animation will replay because I am reassigning the width:
canvas.width = $(window).width();
which will reset the entire context state ( read it here http://diveintohtml5.info/canvas.html)
It works the first time you click the canvas but after that it remembers the context transformation state and shows some weird animation.
I tried adding this:
context.setTransform( 1, 0, 0, 1, 0, 0 );
to explicitly reset the transformation matrix to identity matrix before re-drawing but has no effect.
It is different from this How to clear the canvas for redrawing
because it is about how to clear the display of context but I want to clear everything the display plus the context state.
I tried logging the state of each variable during the animation I get something weird with the ff code.
function moveHorizontal(x){
if(x < 100 ){
context.translate(1, 0);
console.log("x:"+x);
drawImage();
x += 1;
setTimeout(moveHorizontal,10,x);
}
}
I am calling this function initially as moveHorizontal(0).
so the log is as expected the first time:
x:0
x:1
x:2
.
.
x:99
when I click "replay" I get same thing as above:
x:0
x:1
x:2
.
.
x:99
which is correct but when I click "replay" the second time
I am getting this:
x:0
x:0
x:1
x:1
.
.
.
x:99
x:99
which triples the translation leading to unexpected effect.
any explanation?
Update
With the new information this may be the cause of the problem (there is not enough code to be 100% sure but it should give a good pointer as to where the problem is):
As the code is asynchronous and seem to share a global/parent variable x, what happens is that when, at some point, the replay is invoked before one earlier has stopped, the x is reset to 0 causing both (or n number of loops) to continue.
To prevent this you either need to isolate the x variable for each run, or using a simpler approach blocking the loop from running if it's already running using x from a previous invocation. You can use a flag to do this:
var x = 0,
isBusy = false;
function animation(x) {
if (isBusy) return;
if (x < 100) {
isBusy = true;
// ...
setTimeout(...); // etc.
}
else {
isBusy = false;
}
}
optionally, store the timeout ID from setTimeout (reqID = setTimeout(...)) and use clearTimeout(reqID) when you invoke a new loop.
Old answer
The only way to reset the context state entirely is to:
Set a new dimension
Replace it with a new canvas (which technically isn't resetting)
The latter should be unnecessary though.
According to the standard:
When the user agent is to set bitmap dimensions to width and height,
it must run the following steps:
Reset the rendering context to its default state.
...
In the example code in your post you are using a mix of jQuery and vanilla JavaScript. When working with canvas (or video element) I always recommend using vanilla JavaScript only.
Since you are not showing more of the code it is not possible for us to pinpoint to any specific error. But as neither setting an identity matrix nor setting a size for canvas seem to work, it indicates that the problem is in a different part of the code. Perhaps you have persistent offsets involved for your objects that are not reset.
Try to eliminate any possible errors coming from using jQuery to set width as well:
canvas.width = window.innerWidth; // and the same for height
Two other things I notice is that you set the size of canvas inside a function that appears to be part of a loop - if this is the case it should be avoided. The browser will have to, in essence, build a new canvas every time this happens. Second, this line:
canvas.addEventListener("click", replay, false);
can simply be replaced with (based on the code as shown):
canvas.addEventListener("click", animate, false);
You will need to post more code to get a deeper going answer though. But as a conclusion in regards to context: setting a new size will reset it. The problem is likely somewhere else in the code.

HTML5 Audio stop function

I am playing a small audio clip on click of each link in my navigation
HTML Code:
<audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
JS code:
$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
It's working fine so far.
Issue is when a sound clip is already running and i click on any link nothing happens.
I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API
I tried following code but it's not working
$.each($('audio'), function () {
$(this).stop();
});
Any suggestions please?
Instead of stop() you could try with:
sound.pause();
sound.currentTime = 0;
This should have the desired effect.
first you have to set an id for your audio element
in your js :
var ply = document.getElementById('player');
var oldSrc = ply.src;// just to remember the old source
ply.src = "";// to stop the player you have to replace the source with nothing
I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:
player.currentTime = 0 keeps downloading the stream.
player.src = '' raise error event
My solution:
var player = document.getElementById('radio');
player.pause();
player.src = player.src;
And the HTML
<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>
Here is my way of doing stop() method:
Somewhere in code:
audioCh1: document.createElement("audio");
and then in stop():
this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';
In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>
This method works:
audio.pause();
audio.currentTime = 0;
But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.
First method: create a function and pass the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
//then using it:
stopAudio(audio);
Second method (favoured): extend the Audio class:
Audio.prototype.stop = function() {
this.pause();
this.currentTime = 0;
};
I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.
Then you can call the stop function on audio objects:
audio.stop();
FINALLY CHROME ISSUE WITH "canplaythrough":
I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.
So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:
//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
$(this).off("canplaythrough");
// rest of the code ...
});
BONUS:
Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).
For example if you wanted a "restart" method that restarted the audio it could look something like:
Audio.prototype.restart= function() {
this.pause();
this.currentTime = 0;
this.play();
};
It doesn't work sometimes in chrome,
sound.pause();
sound.currentTime = 0;
just change like that,
sound.currentTime = 0;
sound.pause();
From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.
function playStream() {
var player = document.getElementById('player');
(player.paused == true) ? toggle(0) : toggle(1);
}
function toggle(state) {
var player = document.getElementById('player');
var link = document.getElementById('radio-link');
var src = "http://192.81.248.91:8159/;";
switch(state) {
case 0:
player.src = src;
player.load();
player.play();
link.innerHTML = 'Pause';
player_state = 1;
break;
case 1:
player.pause();
player.currentTime = 0;
player.src = '';
link.innerHTML = 'Play';
player_state = 0;
break;
}
}
Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.
As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.
shamangeorge wrote:
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.
This is indeed what will happen, and pausing will also trigger the pause event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay is enabled - setting src to null is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.
This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").
<div id="plHolder">
<audio controls id="player">
...
</audio>
<div>
Then this javascript should work:
function stopAudio() {
var savePlayer = $('#plHolder').html(); // Save player code
$('#player').remove(); // Remove player from DOM
$('#FlHolder').html(savePlayer); // Restore it
}
I was looking for something similar due to making an application that could be used to layer sounds with each other for focus. What I ended up doing was - when selecting a sound, create the audio element with Javascript:
const audio = document.createElement('audio') as HTMLAudioElement;
audio.src = getSoundURL(clickedTrackId);
audio.id = `${clickedTrackId}-audio`;
console.log(audio.id);
audio.volume = 20/100;
audio.load();
audio.play();
Then, append child to document to actually surface the audio element
document.body.appendChild(audio);
Finally, when unselecting audio, you can stop and remove the audio element altogether - this will also stop streaming.
const audio = document.getElementById(`${clickedTrackId}-audio`) as HTMLAudioElement;
audio.pause();
audio.remove();
If you have several audio players on your site and you like to pause all of them:
$('audio').each( function() {
$(this)[0].pause();
});
I believe it would be good to check if the audio is playing state and reset the currentTime property.
if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
sound.currentTime = 0;
}
sound.play();
for me that code working fine. (IE10+)
var Wmp = document.getElementById("MediaPlayer");
Wmp.controls.stop();
<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6"
standby="Loading áudio..." style="width: 100%; height: 170px" id="MediaPlayer">...
Hope this help.
What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:
<audio id="audioplayer" *ngIf="song?.audio_path">
Then when I want to unload it in code I do this:
this.song = Object.assign({},this.song,{audio_path: null});
When the next song is assigned, the control gets completely recreated from scratch:
this.song = this.songOnDeck;
The simple way to get around this error is to catch the error.
audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:
function playSound(sound) {
sfx.pause();
sfx.currentTime = 0;
sfx.src = sound;
sfx.play().catch(e => e);
}
Note: You may want to replace the arrow function with an anonymous function for backward compatibility.
In IE 11 I used combined variant:
player.currentTime = 0;
player.pause();
player.currentTime = 0;
Only 2 times repeat prevents IE from continuing loading media stream after pause() and flooding a disk by that.
What's wrong with simply this?
audio.load()
As stated by the spec and on MDN, respectively:
Playback of any previously playing media resource for this element stops.
Calling load() aborts all ongoing operations involving this media element

How to stop simultaneous browser and SWF mouse wheel scrolling in AS3?

Essentially, I have flash content that scrolls on mouse wheel. It works fine, unless there is other content in the browser such that the browser's scrollbar is enabled - when that is the case, both the browser window AND my SWF scroll on mouse wheel. Is there any way to correct this behavior?
Similar question asked here:
disable mouse wheel scrolling while cursor over flex app?
which references the solution blogged about here:
http://www.spikything.com/blog/index.php/2009/11/27/stop-simultaneous-flash-browser-scrolling/
But the solution does not work on all browsers! While it works on some Windows browsers, it doesn't work at all on Mac OS X - it registers mouse wheel events in Firefox, but they are not getting fired at all in Chrome and Safari.
Now I know that (per the official Adobe InteractiveObject docs) mouse wheel is supposedly only supported on Windows systems, but the event is still fired by default on Mac OS X. Is this simultaneous scroll bug the reason it is not supported?
Edit: adding more info on above solution...
Note that the above solution basically uses ExternalInterface to send the following JavaScript to the "eval" function:
var browserScrolling;
function allowBrowserScroll(value) {
browserScrolling = value;
}
function handle(delta) {
if (!browserScrolling) {
return false;
}
return true;
}
function wheel(event) {
var delta = 0;
if (!event) {
event = window.event;
}
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
} else if (event.detail) {
delta = -event.detail / 3;
}
if (delta) {
handle(delta);
}
if (!browserScrolling) {
if (event.preventDefault) {
event.preventDefault();
}
event.returnValue = false;
}
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
allowBrowserScroll(true);
Is this cat at least on the right path, or is there a better (i.e. fully functional) solution?
I created a small lib that handles everything for you. It works perfect (as far as I tested) on default flash player plugin, on Pepper flash and on MAC-OS. And you don't need to add any .js files to your HTML folder
GIhub repo
You should be able to do this entirely via javascript ...
First off you need to listen to "wheel", "mousewheel" and also to "DOMMouseScroll". It appears DOMMouseScroll is for Firefox only .....
Secondly -- it might be a little bit better to do this entirely in javascript:
// pseudo-code -- this tests for all "Objects" using not-so-standard elementFromPoint;
// You can also look for the element directly using id
var fn = function(e) {
var element = document.elementFromPoint(e.pageX, e.pageY);
if (element && element.tagName === 'OBJECT') {
e.preventDefault();
e.stopPropagation();
}
}
window.addEventListener('DOMMouseScroll', fn);
window.addEventListener('mousewheel', fn);
You may need to test the variations of scroll and mousewheel to access the Webkit events. See here.
I believe you will have to hook the event in JS on the page, then prevent default, and send the event(delta) to your flash. The code you posted looks like it is setting that up somewhat (preventing default) yet I do not see where the code is hooking the DOM.

Flash authoring environment strange Test Movie behavior (AS3)

I can't for the life of me figure out why this is happening. Let me describe what I'm experiencing.
I add everything dynamically via actionscript.
In the Flash authoring environment, when I test the movie, sometimes all of the movieclips on stage disappear and all I see is the color of the Stage.
The strange thing is that I can still rollover/rollout (I added trace statements to my rollover/rollout handlers).
I'm also tracing out the 'visible' and the 'alpha' property and visible=true and alpha=1.0 !!!
On thing that I am seeing is sometimes the rollover/rollout methods get called multiple times in quick succession. I.e. the method invocation order is rollover, rollout, rollover or rollout, rollover, rollout.
The actions that I have in my rollover and rollout methods are really simple. All they do is turn on/off other movieclips...imagine a map...when you rollover an icon, a path shows up on the map and when your rolloff, the path goes away.
However, if I adjust the window of the test movie window, everything appears again!
The crazy thing is that when I publish it, this behavior doesn't happen in the browser or as an app!
What's going on? Could it be a memory thing with the authoring environment?
Posting some code here:
private function rollOverUserListener ( e:MouseEvent ) {
trace(">>>>>>>> rollOverUserListener() e.currentTarget.name : " + e.currentTarget.name);
trace("e.currentTarget.alpha: " + e.currentTarget.alpha);
trace("e.currentTarget.visible: " + e.currentTarget.visible);
e.currentTarget.rollOverAction(); //just scales the icon a little
//fade up/down the appropriate path
worldMap.resetPaths(); //turns off all the paths
for (var i=0; i<users.length; i++){
if ( e.currentTarget == users[i] ) { //highlight the right path
worldMap.highlightPath(i);
}
}
}
private function rollOutUserListener ( e:MouseEvent ) {
trace("<<<<<<<< rollOutUserListener() e.currentTarget.name : " + e.currentTarget.name);
e.currentTarget.rollOutAction(); //scales down the icon to normal
worldMap.resetPaths();
}
I don't think it's efficient to try and solve this problem via posting the code you did.
But, my guess is that the difference in behavior that you are seeing is due to the flash player version.
CS5 or whatever version you have of flash, comes with the latest player at that time. But the flash player is constantly being upgraded, so when you are in your browser -- you most likely have the latest flash player. That could account for the differences you are seeing.
However, the code above doesn't help to much without seeing the highlightPaths and resetPaths functions. I see that you have a trace, but right after that -- there's code executed that could potentially easily change the state of anything you traced before rendering the frame.
Stick some traces after that code to see if you get what you expect.
Are you using any libraries that might have features only supported by a newer flash player ?
private function rollOverUserListener ( e:MouseEvent ) {
trace(">>>>>>>> rollOverUserListener() e.currentTarget.name : " + e.currentTarget.name);
trace("e.currentTarget.alpha: " + e.currentTarget.alpha);
trace("e.currentTarget.visible: " + e.currentTarget.visible);
e.currentTarget.rollOverAction(); //just scales the icon a little
//fade up/down the appropriate path
worldMap.resetPaths(); //turns off all the paths
for (var i=0; i<users.length; i++){
if ( e.currentTarget == users[i] ) { //highlight the right path
worldMap.highlightPath(i);
}
}
}
private function rollOutUserListener ( e:MouseEvent ) {
trace("<<<<<<<< rollOutUserListener() e.currentTarget.name : " + e.currentTarget.name);
e.currentTarget.rollOutAction(); //scales down the icon to normal
worldMap.resetPaths();
}