Transition.translate Easing vs SpringTransition - javascript

I'm currently experimenting a bit with Famo.us and there is actually one thing I can't yet wrap my head around.
In a small example i tried to create a HeaderFooterLayout, where the header contains a simple icon left aligned. A click on it will bounce it to the right end of the header.
Now with a simple Transform.translate this works not as smooth as expected on my Nexus4 and Nexus 7, but hell changing it to a SpringTransition rocks. Here is the code example:
var Transitionable = require('famous/transitions/Transitionable');
var SpringTransition = require('famous/transitions/SpringTransition');
Transitionable.registerMethod('spring', SpringTransition);
var logoStateModifier = new StateModifier({});
var logo = new ImageSurface({
size: [186, 43],
content: 'images/my-logo.png'
});
var posX = 0;
var adjustment = 20;
// Click event on image
logo.on('click', function() {
if(posX === 0) {
posX = (window.innerWidth - logo.size[0] - adjustment);
} else {
posX = 0;
}
var spring = {
method: 'spring',
period: 10,
dampingRatio: 0.3,
};
// transform translate with Easing
logoStateModifier.setTransform(
Transform.translate(posX,0,0),
{ duration: 1000, curve: Easing.inOutBack}
);
// spring transition
logoStateModifier.setTransform(
Transform.translate(posX, 0, 0), spring
);
});
So what I don't understand here is why Easing is so "slow" compared to the Physics driven SpringTransition?

The spring transition your requesting has a period of 10ms while the easing transition is 1000ms or 100 times slower. I tried your code "as is" and with a modification that compares more apples to apples and the transitions can run at the same speed (both laptop and devices.) First you should note that the minimum spring period is 150ms so the 10ms your asking for is actually 150. Second you are stacking the transitions so that one follows the other. The easing will take 1 second and then the spring will oscillate. You may want to try something slightly different... set the transitions to the following:
// transform translate with Easing
logoStateModifier.setTransform(
Transform.translate(posX,0,0),
{ duration: 150, curve: Easing.inOutBack}
);
// spring transition
logoStateModifier.setTransform(
Transform.translate(0, 0, 0), spring
);
This will behave slightly differently. On click (every other click actually) the logo will cross the screen at high speed and then come back. I expect you'll find that these transitions run at comparable high speeds. Of course for a slower more viewable test you can set the spring period to 1000 and the easing duration to the same and again the speeds should be comparable.

Related

Any way to update the duration of an animation set via element.animate without restarting the animation?

I'm developing a game engine in HTML5. Characters are div elements using an animated sprite for background. As sprite animation have fluid parameters and must be set by code, they can't be predefined in a static CSS definition, thus I use element.animate to set sprite animations to a given row at a given speed knowing my scales and frame counts.
// Applies the given frame and animation to the sprite
// Frame is an angle, clockwise direction: 0 = up, 1 = right, 2 = down, 3 = left
set_animation(frame, duration) {
const scale_x = this.settings.sprite.scale_x * this.settings.sprite.frames_x;
const pos_y = this.settings.sprite.scale_y * -frame;
// Cancel the existing animation
if(this.data_actors_self.anim) {
this.data_actors_self.anim.cancel();
this.data_actors_self.anim = null;
}
// Play the animation for this row or show the first frame if static
if(duration > 0) {
this.data_actors_self.anim = this.element.animate([
{
backgroundPosition: px([0, pos_y])
}, {
backgroundPosition: px([scale_x, pos_y])
}
], {
duration: duration * 1000,
direction: "normal",
easing: "steps(" + this.settings.sprite.frames_x + ")",
iterations: Infinity
});
this.data_actors_self.anim.play();
} else {
this.element.style.backgroundPosition = px([0, pos_y]);
}
}
Obviously that's a snippet from an actor class function: this.element is the div, this.settings is an object with parameters to be used who's names should make sense in this context, the px() function is a simple converter to turn arrays into pixel strings for HTML (eg: [0, 0] to "0px 0px").
The issue I'm having: While I can always run this function to set a new animation, I want the ability to change the speed of the animation without resetting it. It doesn't need to be a smooth transition, for all I care the new speed can be applied at the next iteration... I only want to avoid a visual snap or any kind of reset upon applying the change. Once an animation is set, I have no idea how to access and update its duration parameter. Does anyone have any suggestions?
When using console.log on this.data.anim I'm rightfully told it's an animation object. I tried using JSON.stringify to get more information but nothing relevant is printed. this.data.anim.duration returns undefined so the setting must be stored under some other property. Even if I know that property, I'd like to be sure web browsers will agree with me changing it like this.data.anim.options.duration = new_duration.
You can wait for the end of an iteration before changing the animation duration if that is what is required.
This snippet only sets an event listener for animationiteration event when you click the button to increase the speed.
function upthespeed() {
const div = document.querySelector('div');
div.addEventListener('animationiteration', function() {
div.style.animationDuration = '1s';
});
document.querySelector('button').style.display = 'none';
}
div {
width: 10vmin;
height: 10vmin;
background-color: magenta;
animation: move 10s linear infinite;
}
#keyframes move {
0% {
transform: translateX(50vw);
}
50% {
transform: translateX(0);
}
100% {
transform: translateX(50vw);
}
}
<div></div>
<button onclick="upthespeed()">Click me to increase the speed at the end of the next iteration (you may have to wait!)</button>
The value for the animation duration isn't in the Animation object itself but in the CSS animation-duration property for the Element: so this.data_actors_self.style.animationDuration = new_duration will do the job. It will however restart the animation if it is being played, but if I understand correctly that isn't a problem for you.
Edit: To change the animation's duration without restarting it, all you have to do is set the value of anim.startTime to what it was before. For example:
const startTime = anim.startTime;
this.data_actors_self.style.animationDuration = new_duration
anim.startTime = startTime;

Improving performance of infinite scrolling animation

I have long list of elements with svg icons(60-70 elements) and I want to animate it so it looks like infinite scrolling. I am using animejs library and animating translateY property of the g group which contains all elements. This works ok but performance is not very good. I am already using will-change: transform CSS attribute for the g tags which are being animated. I am animating just single translateY transform, why is performance so poor? How can I improve performance?
I could try to have only elements required to cover the screen and then animate these elements instead. But that would require constantly changing "src" attribute of the elements which come from off screen and I feel like would be even slower.
Should I replace SVG icons with png? I feel like this should not affect animation performance.
Unfortunately I can't use CSS animations because I need to sync this animation with some other animations on the page.
let initialOffset = 0;
let currentOffset = 0;
anime({
target: '.group-of-boxes',
duration: 1000,
easing: 'linear',
loop: true,
loopBegin: function(anim) {
initialOffset = currentOffset;
},
update: function(anim) {
const d = 100 * anim.progress / 100;
currentOffset = clipOffset(initialOffset + d, object);
anime.set(target , {
translateY: currentOffset
});
}
});

Smooth DeviceOrientation Values

I'm trying to shift an image around based on the device orientation. But the values are very jumpy at rest, going between -1 to +2 with no movement, and I need a way to smooth it out a bit.
Is there an easy way to make this less jittery by averaging it out or something?
init();
var count = 0;
function init() {
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', function(eventData) {
// gamma is the left-to-right tilt in degrees, where right is positive
var tiltLR = eventData.gamma;
// beta is the front-to-back tilt in degrees, where front is positive
var tiltFB = eventData.beta;
// alpha is the compass direction the device is facing in degrees
var dir = eventData.alpha
// call our orientation event handler
deviceOrientationHandler(tiltLR, tiltFB, dir);
}, false);
}
}
function deviceOrientationHandler(tiltLR, tiltFB, dir) {
var logo = document.getElementById("imgLogo");
logo.style.webkitTransform = "rotate("+ tiltLR +"deg) rotate3d(1,0,0, "+ (tiltFB*-1)+"deg)";
logo.style.MozTransform = "rotate("+ tiltLR +"deg)";
logo.style.transform = "rotate("+ tiltLR +"deg) rotate3d(1,0,0, "+ (tiltFB*-1)+"deg)";
}
http://codepen.io/picard102/pen/zvOVLx
Use CSS transitions to smooth out setting CSS values.
You can try adding transition: all 0.5s;-webkit-transition: all 0.5s; to your logo. This will cause the browser to smoothly transition from one transform state to the next.
You might need to experiment a bit with this setting; and you may have to implement your own smoothing instead (in JavaScript, using JavaScript-based animation) if you're not happy with the results of CSS transition.

How to animate slide left smoothly?

I have the following
$('.left_arrow').hover(function() {
$('.chart').stop().animate({
left: "+=10"
});
},
function() {
$('.chart').stop();
});
And I want to have it when you mouse over the arrow it smoothly moves the .chart to the left, and the right arrow it moves it to the right. I am doing this by applying a - left (-7500px is the max) to move it to the left and a 0 is the farthest it can go right.
The above moves it over 10, but it doesn't keep on moving it. How can I get it so it keeps on moving it. I was using something like
$('.left_arrow').hover(function() {
$('.chart').stop().animate({
left: "-7500px"
}, 20000);
},
function() {
$('.chart').stop();
});
But the problem is if I am say -6500px over it takes 20 seconds to go the rest of the 1000, vs 20 seconds to go the full distance. So the speed is skewed, I want a standard increment.
Basically what you need is a rate function. I had the same issue when I was creating my carousel.
rate = distance/time
So, your rate is 0.375
Now, all you will need to do is find the distance and you can adjust your timing accordingly.
time = distance/0.375
So it should look something like this:
$('.left_arrow').hover(function() {
var distance = /*Get Distance Remaining*/
var sd = 7500;
var time = 20000;
var rate = sd/time;
var time = distance/rate
$('.chart').stop().animate({
left: "-7500px"
}, time);
},
function() {
$('.chart').stop();
});
Obviously it would need some tweaking to get just right. But the concept is there.
For my situation, because I was using a <ul> since it was a carousel this is the way I got distance:
distance = Math.abs($ul.position().left);
Not fully understanding the question, but you can increment/decrement animations like so:
$('.chart').stop().animate({
"left": "+=100px"
}, 250);
Note the += operator.
EDIT: This answer is only partially correct. Animation behavior on hover is not as desired. Trying to solve.

Animation starts moving out of position after some time

I am trying to create a sort of slideshow animation. I have the codes here: jsFiddle.
These tablets would rotate around.
The problem is that, at random times, the animation will move out of line. The wrong tablets undergo wrong animations. Here are the screenshots:
And this is how it looks like when the animations goes wrong
The main problem is I don't understand why the animation would go wrong random times. In my computer it will run properly for hours, but in other cases (especially on Safari).
You could store the expected final css values for each animated el and then in the animate callback set these values, so for each animated el something like
var el = $(selector);
el.data("finalCSS", { your expected final CSS values })
$("selector").animate({animation properties}, function() {
el.css(el.data("finalCSS")).data("finalCSS", undefined);
})
This doesn't help with figuring out why it's happening (but I can't recreate the issue myself), but provides a failsafe to make sure the layout doesn't break;
I believe this happens when you try to animate before the previous animation has ended. Use jQuery stop() just before you animate. For example:
$('#animatingDiv').stop(false, true).animate({height:300}, 200, callback);
The first param(false) will empty the animation queue on that element and the second param(true) will jumps to the end of current animation before starting a new animation.
You can do this with far less code and far fewer headaches.
1. Store your tablet position attributes in classes
.tablet1{
height:100px;
width:140px;
margin-left:-540px;
top: 200px;
z-index:10;
}
2. Use a general function to handle all your transitions.
JQuery UI will do all the work for you if you use switchClass
switchTabletsRight = function(){
var i, next, max = 5;
for(i = 1; i <= max; i++){
next = (i < max)? i + 1 : 1;
$(".tablet" + i).switchClass("tablet" + i, "tablet" + next);
}
};​
Here's the JSfiddle proof of concept: http://jsfiddle.net/nRHag/4/
You are setting CSS positions to decimal values.
img_w = $("#tablet"+num+" img").width();
img_w = img_w *140 / 600;
img_h = $("#tablet"+num+" img").height();
img_h = img_h *140 /600;
...
var new_width = $(this).width() * 140 / 600;
$(this).css('width', new_width);
var new_height = $(this).height() * 140 / 600;
$(this).css('height', new_height);
Your division could be cause decimal results which have different effects in different browsers. Sub pixel CSS positioning may be creating your unintended errors.

Categories