raphael multiple animations on same set - javascript

I asynchronously receive new positions of element. Each time I receive the position I calculate the offset and move the element (set), like this:
asynchReceiveData(id,function(newposition){
var offset = {};
var oldposition = getOldPosition(markerArray[id]); //returns object with old x and y
offset.x = (newposition.x - oldposition.x);
offset.y = (newposition.y - oldposition.y);
markerArray[id].entireSet.stop()
.animate({ transform:"...T"+offset.x+","+offset.y }, 400);
//i also tried without .stop()
});
For example:
with each update the set should move 50px to the right, after 10 slow updates (lets say one update per 2 seconds), the set is 500px to the right, everything is OK.
Problem is, when I receive too many new positions too fast:
(e.g. one update per 200ms),then the set is 300, or 350 or 400 or 450 instead of 500px to the right.
I think the problem is that the animation does not have enough time to finish before new animation is triggered. I tried lowering the animation time from 400ms to 200, but with little success, it still sometimes happened.
Everything works fine, when I do not use animation and do just this:
markerArray[id].entireSet.transform("...T"+offset.x+","+offset.y);
But I would like to have this animations. Do you have any suggestion how to fix this?

So.. after few tries I came to a solution:
After the end of every animation I check the real position of element (with getBBox()) and compare it with expected position. If it differs I move the element by the difference; In code:
asynchReceiveData(id,function(newposition){
var offset = {};
var oldposition = getOldPosition(markerArray[id]); //returns object with old x and y
offset.x = (newposition.x - oldposition.x);
offset.y = (newposition.y - oldposition.y);
markerArray[id].entireSet.stop().animate({ transform:"...T"+offset.x+","+offset.y}, 500,
function () {
var o = {};
o.x = markerArray[id].x - markerArray[id].circleObj.getBBox().cx;
o.y = markerArray[id].y - markerArray[id].circleObj.getBBox().cy;
markerArray[id].entireSet.transform("...T"+o.x+","+o.y);
});
});
Sometimes it's not very smooth (a bit laggy), but anyway, it solves the problem.

Related

Applying cubic bezier function to animate a property change

I'm experimenting in Javascript with animating various elements using a cubic-bezier timing function.
(I know this is usually better done with CSS3, or a Javascript animation library. I'm simply using Javascript here to understand how bezier functions work, and teach myself about them.)
So, I get the basic concept, and I'm using a simple bezier curve library written by Stephen McKamey, which is a great Javascript port of the Webkit implementation.
I'm having trouble understanding how I can actually use this function to control an animation in Javascript. So, starting with something very simple: a basic black square that I can animate by moving it to the right, by incrementing its style.left property:
CSS:
.parent {
position: relative;
}
.foo {
border: 1px solid #000000;
background-color: black;
height: 200px;
width: 200px;
position: absolute;
}
HTML:
<div class = "parent">
<div class = "foo" id = "target"></div>
</div>
Okay, so, given a cubic bezier function "bezier", defined as follows:
function bezier(p1x, p1y, p2x, p2y, x, duration) { ... }
Where p1x, p1y, p2x and p2y are the curve control points (between 0 and 1.0), x is the value of the x coordinate, and duration is a duration in milliseconds. The function returns the corresponding y coordinate. I'm trying to simply animate this black box by moving it 400px to the right.
For my first attempt, I use the standard "ease" bezier values, which CSS3 uses, so our ease bezier function could be written as:
function ease(x, duration) {
return function() {
Bezier.cubicBezier(0.25, 0.1, 0.25, 1.0, x, duration);
}
}
So this should give us a slow start, then move fast, then end slowly.
Okay, so I assume the basic way to implement this is to use window.setInterval, and then for each interval, call the bezier function with a new value for x, and then apply the result somehow to the property we want to animate.
The thing is, I'm not sure what my "x" value is here. I assume that in this situation, x is actually the time, and y is the delta between the old position and new position (distance to move), but I'm not really sure. I'm probably wrong.
Anyway, plugging this all in, I'd write a function like:
var startPos = 0;
var endPos = 400; // pixels
var duration = 400; // milliseconds
var millisecondsPerInterval = 10;
var target = document.getElementById("target");
var t = 0;
var pos = 0;
var bezierFunction = Bezier.cubicBezier;
var interval = window.setInterval(
function() {
pos = pos + bezierFunction(0.25, 0.1, 0.25, 1.0, t / 1000, duration); // "ease" values
target.style.left = (pos * millisecondsPerInterval) + "px";
t += millisecondsPerInterval;
if (t === duration) { window.clearInterval(interval); }
},
millisecondsPerInterval
);
This seems to work - the box slowly begins moving and then speeds up. But then it just stops abruptly, rather than easing out. So I'm probably not applying this function correctly. I'm not even certain if "x" is supposed to be my time value here, and "y" is supposed to be the position delta (distance to move), but that seems the only way to apply this that makes any sense.
So, am I doing something wrong here? What is the correct way to apply a cubic bezier function to a property we want to animate using Javascript?
If you use JQuery, it may make the process simpler.
Based on an answer to a similar question (https://stackoverflow.com/a/6824695/363099), you could extend jQuery easing in order to add your custom easing function:
According to the jQuery 1.6.2 source, the meaning of the easing function is as follows. The function is called at various points in time during the animation. At the instants it is called,
x and t both say what the time is now, relative to the start of the animation. x is expressed as a floating point number in the range
[0,1], where 0 is the start and 1 is the end. t is expressed in
milliseconds since the start of the animation.
d is the duration of the animation, as specified in the animate call, in milliseconds.
b=0 and c=1.
So here is how it could work for your code:
$.extend(jQuery.easing,{bezier: function(x,t,b,c,d) {
return (
x <= 0 ? 0 :
x >= 1 ? 1 :
bezierFunction(0.25, 0.1, 0.25, 1.0, x, d)
);
} });
Then you can just use JQuery animation function:
$('#target').animate({right:'400px'},400,'bezier');

famo.us trigger event at key point of animation

I'm trying to trigger an event half-way through the progress (not time) of a transition. It sounds simple, but since the transition can have any curve it's quite tricky. In my particular case it's not going to be paused or anything so that consideration is out of the way.
(Simplified) essentially I could trigger an animation on a modifier like this:
function scaleModifierTo(stateModifier, scale, animationDuration) {
stateModifier.setTransform(
Transform.scale(scale, scale, scale),
{
duration: animationDuration,
curve: this.options.curve
}
);
}
When the interpolated state of the Transitionable hits 0.5 (half-way through) I want to trigger a function.
I haven't dug that deep behind in the source of famo.us yet, but maybe need to do something like
subclass something and add the possibility to listen when the state passes through a certain point?
reverse the curve defined and use a setTimeout (or try to find a proximity using a few iterations of the chosen curve algorithm (ew))
Is it possible to do this easily? What route should I go down?
I can think of a couple of ways to achieve such, and both lend to the use of Modifier over StateModifier. If you are new, and haven't really had the chance to explore the differences, Modifier consumes state from the transformFrom method which takes a function that returns a transform. This is where we can use our own Transitionable to supply state over the lifetime of our modifier.
To achieve what you wish, I used a Modifier with a basic transformFrom that will alter the X position of the surface based on the value of the Transitionable. I can then monitor the transitionable to determine when it is closest, or in my case greater than or equal to half of the final value. The prerender function will be called and checked on every tick of the engine, and is unbinded when we hit the target.
Here is that example..
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var Transitionable = require('famous/transitions/Transitionable');
var SnapTransition = require('famous/transitions/SnapTransition');
Transitionable.registerMethod('snap',SnapTransition);
var snap = { method:'snap', period:1000, damping:0.6};
var context = Engine.createContext();
var surface = new Surface({
size:[200,200],
properties:{
backgroundColor:'green'
}
});
surface.trans = new Transitionable(0);
surface.mod = new Modifier();
surface.mod.transformFrom(function(){
return Transform.translate(surface.trans.get(),0,0);
});
context.add(surface.mod).add(surface);
function triggerTransform(newValue, transition) {
var prerender = function(){
var pos = surface.trans.get();
if (pos >= (newValue / 2.0)) {
// Do Something.. Emit event etc..
console.log("Hello at position: "+pos);
Engine.removeListener('prerender',prerender);
}
}
Engine.on('prerender',prerender);
surface.trans.halt();
surface.trans.set(newValue,transition);
}
surface.on('click',function(){ triggerTransform(400, snap); });
The downside of this example is the fact that you are querying the transitionable twice. An alternative is to add your transitionable check right in the transformFrom method. This could get a bit strange, but essentially we are modifying our transformFrom method until we hit our target value, then we revert back to the original transformFrom method.. triggerTransform would be defined as follows..
Hope this helps!
function triggerTransform(newValue, transition) {
surface.mod.transformFrom(function(){
pos = surface.trans.get()
if (pos >= newValue/2.0) {
// Do something
console.log("Hello from position: " + pos)
surface.mod.transformFrom(function(){
return Transform.translate(surface.trans.get(),0,0);
});
}
return Transform.translate(pos,0,0)
})
surface.trans.set(newValue,transition);
}
Thank you for your responses, especially #johntraver for the prerender event, I wasn't aware of the existence of that event.
I realised it made more sense that I should handle this logic together with my move animation, not the scale one. Then, I ended up using a (very hacky) way of accessing the current state of the transition and by defining a threshold in px I can trigger my function when needed.
/**
* Move view at index to a specified offset
* #param {Number} index
* #param {Number} xOffset xOffset to move to
* #param {Object} animation Animation properties
* #return void
*/
function moveView(index, xOffset, animation) {
var rectModifier = this._views[index].modifiers.rect;
var baseXOffset = rectModifier._transformState.translate.state[0];
// After how long movement is reflow needed?
// for the sake of this example I use half the distance of the animation
var moveThreshold = Math.abs(baseXOffset - xOffset)/2;
/**
* Callback function triggered on each animation frame to see if the view is now covering
* the opposite so we can trigger a reflow of the z index
* #return void
*/
var prerender = function() {
var numPixelsMoved = Math.abs(baseXOffset - rectModifier._transformState.translate.state[0]);
if (numPixelsMoved > moveThreshold) {
Engine.removeListener('prerender', prerender);
// trigger a method when this is reached
_reflowZIndex.call(this);
}
}.bind(this);
rectModifier.setTransform(
Transform.translate(xOffset, 0, 0),
animation,
function() {
Engine.removeListener('prerender', prerender);
}
);
Engine.on('prerender', prerender);
}
Obviously the ._transformState.translate.state[0] is a complete hack, but I couldn't figure out of getting this value in a clean way without adding my own Transitionable, which I don't want. If there is a cleaner way of finding the current state as a Number between 0.0-1.0 that would be ace; anyone knows of one?

ThreeJS - how to set current time in Animation

I'm using skinning / skeletal animation in ThreeJS. I have an animation, and I want to be able to move backward and forward through it, and jump to different locations within it, rather than the usual looping behaviour.
The animation is created like this, as in the example:
var animation = new THREE.Animation( mesh, geometry.animation.name );
I have tried updating the animation with negative deltas, as well as setting animation.currentTime directly:
animation.currentTime = animationLocation;
These appear to work only if I move forward in time, but if I go backward the animation breaks and I get an error:
THREE.Animation.update: Warning! Scale out of bounds: ... on bone ...
One thing that does actually work without error is to call stop() and then play() with a new start time:
animation.stop();
animation.play( true, animationLocation );
...however when I look at what these functions are actually doing, they involve many many function calls, looping, resetting transforms etc. This seems like a horrible way to do it, even if it works as a hack.
It may be that this functionality does not exist yet, in which case I'll try to dig in and create a function that does a minimal amount of work, but I'm hoping there is another way that I haven't found.
Can anyone help with this?
[UPDATE]
As an update on my progress, I'll post the best solution I have at this time...
I pulled out the contents of the stop() and play() functions, and stripped out everything I could, making some assumptions about certain values having already been set by 'play()'.
This still seems like it is probably not the best way to do it, but it is doing a bit less work than by just calling stop() then play().
This is what I was able to get it down to:
THREE.Animation.prototype.gotoTime = function( time ) {
//clamp to duration of the animation:
time = THREE.Math.clamp( time, 0, this.length );
this.currentTime = time;
// reset key cache
var h, hl = this.hierarchy.length,
object;
for ( h = 0; h < hl; h ++ ) {
object = this.hierarchy[ h ];
var prevKey = object.animationCache.prevKey;
var nextKey = object.animationCache.nextKey;
prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
}
//isPlaying must be true for update to work due to "early out"
//so remember the current play state:
var wasPlaying = this.isPlaying;
this.isPlaying = true;
//update with a delta time of zero:
this.update( 0 );
//reset the play state:
this.isPlaying = wasPlaying;
}
The main limitation of the function in terms of usefulness is that you can't interpolate from one arbitrary time to another. You can basically just scrub around in the animation.
You can use THREE.Clock and assign startTime, oldTime, elapsedTime.

HTML canvas double buffering frame-rate issues

I have a full-screen canvas with 3 images drawn on it. When I resize the window, these images change position; however, it appears to be very glitchy, more so in Firefox.
I've been reading that double-buffering should resolve this issue, but I'm wondering how I would double buffer when the next position is unknown. That is to say, I cannot determine what should be buffered in the future, so how would this be possible?
Here is one source that seems doable, but I do not fully understand the concept Fedor is trying to explain.
Does HTML5/Canvas Support Double Buffering?
So far I have,
$canvas = $('#myclouds')[0];
$canvas_buffer = $('canvas')[0].insertAfter($canvas).css('visibility', 'hidden');
context = $canvas.getContext('2d');
context_buffer = $canvas_buffer.getContext('2d');
clouds_arr = [$canvas, $canvas_buffer];
$(window).resize(function () {
drawCanvas();
};
function initCanvas() {
// Sources for cloud images
var cloud1 = '/js/application/home/images/cloud1.png',
cloud2 = '/js/application/home/images/cloud2.png',
cloud3 = '/js/application/home/images/cloud3.png';
// add clouds to be drawn
// parameters are as follows:
// image source, x, y, ratio, adjustment)
addCloud(cloud1, null, 125, .03);
addCloud(cloud2, null, 75, .15);
addCloud(cloud3, null, 50, .55);
addCloud(cloud1, null, 125, .97, 300);
addCloud(cloud2, null, 70, .85, 300);
addCloud(cloud3, null, 45, .5, 300);
// Draw the canvas
drawCanvas();
}
function drawCanvas() {
// Reset
$canvas.attr('height', $window.height()).attr('width', $window.width());
// draw the clouds
var l = clouds.length;
for (var i = 0; i < l; i++) {
clouds[i].x = ($window.width() * clouds[i].ratio) - clouds[i].offset;
drawimage(context, clouds[i]);
}
}
function Cloud() {
this.x = 0;
this.y = 0;
}
function addCloud(path, x, y, ratio, offset) {
var c = new Cloud;
c.x = x;
c.y = y;
c.path = path;
c.ratio = ratio || 0;
c.offset = offset || 0;
clouds.push(c);
}
function drawimage(ctx, image) {
var clouds_obj = new Image();
clouds_obj.src = image.path;
clouds_obj.onload = function() {
ctx.drawImage(clouds_obj, image.x, image.y);
};
}
I think maybe you are misunderstanding what double buffering is. Its a technique for smooth real-time rendering of graphics on a display.
The concept is you have two buffers. Only one is visible at any one time. When you go to draw the elements that make up a frame you draw them to the invisible buffer. In you case the clouds. Then you flip the buffers making the hidden one visible and the visible one hidden. Then on the next frame you draw to the now newly hidden buffer. Then at the end of drawing you flip back.
What this does is stop the user seeing partial rendering of elements before a frame is complete. On gaming systems this would also be synced up with the vertical refresh of the display to be really smooth and stop artefacts such as tearing to occur.
Looking at you code above you seem to have created the two canvas elements, but you're only using the first Context object. I assume this is incomplete as no flipping is taking place.
Its also worth noting that the window resize event can fire continuously when dragging which can cause frantic rendering. I usually create a timer on the resize event to actually re-render. This way the re-render only happens once the user stops resizing for a few milliseconds.
Also, your draw routine is creating new Image objects every time which you don't need to do. You can use one image object and render to the canvas multiple times. This will speed up your render considerably.
Hope this helps.

YUI API Dual Slider control question

I'm using the YUI 2.7 library to handle a dual-slider (range slider) control in a webpage.
It works great-- however, I wanted to allow users to switch the range values by Ajax-- effectively changing the price range from "0-50,000" to a subset (eg. "50-250") without reloading the page.
The problem is that it appears the values from the existing slider do not get reset, even when I explicitly set them back to NULL inside the function to "rebuild" the slider.
The slider handles appear out of position after the ajax request, (way off the scale to the right) and the values of the slider apparently randomly fluctuate.
Is there a way to explicitly destroy the YUI slider object, beyond setting its reference to null? Or do I just need to redeclare the scale and min/max values somehow?
Thanks for any help (I'll try to post a link to an example asap)
here's the code:
function slider(bg,minthumb,maxthumb,minvalue,maxvalue,startmin,startmax,aSliderName,soptions) {
var scaleFactor = null;
var tickSize = null;
var range = null;
var dual_slider = null;
var initVals = null;
var Dom = null;
range = options.sliderLength;
if ((startmax - startmin) < soptions.sliderLength) {
tickSize = (soptions.sliderLength / (startmax - startmin));
}else{
tickSize = 1;
}
initVals = [ 0,soptions.sliderLength ], // Values assigned during instantiation
//Event = YAHOO.util.Event,
dual_slider,
scaleFactor = ((startmax - startmin) / soptions.sliderLength);
dual_slider = YAHOO.widget.Slider.getHorizDualSlider(
bg,minthumb,maxthumb,range, tickSize, initVals);
dual_slider.subscribe("change", function(instance) {
priceMin = (dual_slider.minVal * scaleFactor) + startmin;
priceMax = (dual_slider.maxVal * scaleFactor) + startmin;
});
dual_slider.subscribe("slideEnd", function(){ alert(priceMin + ' ' + priceMax); });
return dual_slider;
}
Store the startmin, startmax, and scaleFactor on the dual_slider object, then in your ajax callback, update those properties with new values. Change your change event subscriber to reference this.startmin, this.startmax, and this.scaleFactor.
Slider and DualSlider only really understand the pixel offsets of the thumbs, and report the values as such. As you've done (and per most Slider examples), you need to apply a conversion factor to translate a pixel offset to a "value". This common idiom has been rolled into the core logic of the YUI 3 Slider (though there isn't yet a DualSlider in the library).
Here's an example that illustrates dynamically updating value ranges:
http://yuiblog.com/sandbox/yui/v282/examples/slider/slider_factor_change.html

Categories

Resources