CSS/JS scrolling glitch effect (performance) - javascript

I am trying to achieve a "crt-like" scrolling glitch effect using Javascript and CSS. I have come up with the following code which clones the content and applies clip to make it look like it scrolls while adding random horizontal offset.
function scanglitch() {
var e = $('#wrapper').clone().appendTo('#glitchcontainer');
var i = 0;
e.css({"clip": "rect(" + i + "px,3830px," + (i + 15) + "px,0px)"});
e.css("z-index",200);
var interval = setInterval(function () {
e.css({"clip": "rect(" + i + "px,3830px," + (i + 15) + "px,0px)"});
e.css({"left": Math.round(Math.random() * 10) + "px"});
i+=4;
if (i > window.innerHeight) {
e.remove();
window.clearInterval(interval);
}
}, 40);
}
Fiddle (Click on the text to see the effect)
I am actually quite pleased with the effect, but the implementation is obviously a hack. As a result the performance is unacceptably low (chrome cpu usage spikes from 5% to 50% when the effect is triggered).
Could someone help me figure out a way to achieve this effect in a more elegant and less performance-heavy way?
UPDATE:
I have implemented your suggestions: Using translate instead of left, scrolling with translate instead of a js loop, calculations outside of the css tag and using requestAnimationFrame(). The code is nicer and more predictable now, but the animations are still very taxing.
New fiddle

You can try using requestAnimationFrame (it is available in almost all browsers). Seems to make a big difference in Chrome.
JSFiddle
EDIT
Here's a transition-only version, and while it doesn't even implement the jitter, it's useful for comparison. Surprisingly(?) it shows about the same, if not more, CPU usage. (You can check the Profile and Timeline tabs in Chrome)
CSS3 Transition-Only JSFiddle
Here's some information about why that should be expected. Essentially, CSS transitions and requestAnimationFrame work very similarly under the hood.

I would delegate as much as possible to css transitions. So instead of moving the clip with js in the interval callback, transition it from top to bottom (example of transitioning).
You could try something similar with the left property, there's no random easing function but maybe you could achieve something similar with one of the bounce functions. Maybe change the easing function with an interval that's less frequent than your current one.
Also, just by slowing the interval of your current solution you'd get visually ok results with less CPU usage.
Side-note: for a completely different route you can replicate your html in a canvas and apply some effects to that. Google has plenty of results for "canvas glitch".
Update: here's my version of your latest fiddle
I get about 10 % less cpu usage with it when comparing to yours. Key differences are:
uses a timeout instead of requestAnimationFrame. requestAnimationFrame is meant to keep framerate high and the animation smooth but we don't need that for the random offsetting. Timeout is also better than an interval since the loop function is quaranteed to finish before next iteration starts.
removed the transparent background, since transparency has a rendering cost

Related

Javascript Intval Show/Hide Flickering

I'm trying to cycle real fast through a series of images to produce an animation using the below setInterval. However, if I move focus away from the browser tab and then back again, the animation flickers.
I saw a thread about using "real time" to catch the animation up, but since mine uses a simple show/hide, I wasn't sure how that applied.
var animation = setInterval(function(){
var visible = $j('#container img:visible');
var next = visible.next('img');
if(next.length <= 0) next = $j('#container img:first');
next.show();
visible.hide();
},64);
Any thoughts on how to combat the flickering?
Traditionally, JavaScript animation can be handled a number of ways. One approach involves using a timing function such as setTimeout or setInterval to adjust styling every couple milliseconds. Another approach creates a loop that changes styling as many times as possible along the animation’s time frame. The logic of both of these approaches is to throw a large number of animation frames at the browser, so that it hopefully renders smooth-looking motion.
So, even though the browser renders as many frames of the animation as possible, the dropped frames still make for a choppy-looking animation, which is not to mention the performance implications of overloading the processor with as many tasks as possible.
In reality, it’s actually better to render fewer frames, provided they are rendered consistently. That’s because our eyes pick up these subtle variations, and a few dropped frames tend to stick out more than an overall lower frame rate. That’s where HTML5′s requestAnimationFrame API comes in.
Here is an example for your scenario:
function animation(){
var visible = $('#container img:visible');
var next = visible.next('img');
if(next.length <= 0) next = $('#container img:first');
next.show();
visible.hide();
};
setInterval(function() {
window.requestAnimationFrame(animation);
}, 64);
DEMO

Is it okay to use .animate with 0 duration all the time? Is there a better alternative?

I've grown used to code my jquery animation by doing the following.
Set the initial state of the element (things like width, height, top, left, opacity, etc...) using either css or javascript. This initial state is the state at the end of the animation.
Use .animate with 0 duration to move the element to the state in which elements are at the beginning of the animation.
Use a regular .animate with the appropriate duration to do the animation in which at the end, the elements are back to state in step 1.
Here is an example.
/* css file */
.animatedObject
{
width:60%;
}
// javascript file
$('.animatedObject')
.animate({width: '-=20%'}, 0)
.animate({width: '+=20%'}, 1000);
There are several advantage using this code at least for me. First, it looks clear to me what I'm trying to animate. Second, if javascript is disabled, the object would be at the end state of the animation which is often where I want it to be for graceful degradation. Third, objects can change position slightly for adjustments using css and the animation would still look largely the same.
The reason I'm not using the .css is that it if I try to replace the animate with 0 duration with the .css method, I would get differing animation starting point. I don't think it support += or -=, or if it does, it behaves differently.
So, is this a good way to do this? What is the industry standard way?
Well you could still use .css():
var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
width: '+=20%'
}, 1000);
I believe this would work faster.
Edit:
I did a little benchmark for you, using jsperf.com. Here are my results (using Google Chrome):
.animate({}, 0)
Code:
$('.animatedObject')
.animate({width: '-=20%'}, 0)
.animate({width: '+=20%'}, 1000);
End Results:
10,013 operations per second
±7.48%
fastest
.css();
Code:
var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
width: '+=20%'
}, 1000);
End Results:
2,477 operations per second
±6.39%
75% slower
Conclusion
Keep the animation function. It turns out using .css() is actually slower. I guess it's the fact that you have 2 extra functions. It's not worth it. This was actually a surprise to me as I thought .css() would function faster than it did. Test this yourself in your browser!

Subtle font size animation over short distances with long durations in jQuery

I want to animate some text in a slow and subtle way. jQuery animations work with integer values, so if you want to animate a size over say 10px in two seconds, you see a series of small steps at five FPS which looks jerky.
Here's a jsFiddle that shows what I'm talking about.
I found a similar question about animating positions, but the top/left/etc properties are integral, and so the accepted answer says it's not possible. However font-size can be animated as a real number, if jQuery will spit real numbers out.
I will also want to chain together a series of such animations.
Any ideas?
I had another look a the minimum point value which is visually recognisable. The smallest unit for pt I noticed change in was 0.2pt.
However, I noticed that when applying the change in steps of 0.2 points over a period of 1 millisecond per increment in a while loop that it still looked a little "laggy". May not if not running in jsfiddle though.
The point is that if you want to change the font-size smoothly by 10 points you must apply the change in steps of 0.2pt or 0.25pt or 0.5pt (what ever you find smoothest) at a time and you then must use an interval of 1 to stay smooth but you should not apply a different interval as otherwise the incremental steps are to small to notice and the whole animation ends up choppy again.
I think trying to force this 10pt change over 2 seconds will always look choppy no matter what framework you use, due to the lack of visual change on the font-size in the lower decimals.
This worked for me quite well:
(I'm not taking decreasing font-size animation into account in this example but that can be added off course)
function smoothAnimation($selector, startPoints, points){
var increments = 0.2;
var currentPoints = startPoints;
var endPoints = currentPoints + points;
while(currentPoints < endPoints){
currentPoints += increments;
$selector.animate({"font-size": currentPoints.toString() + "pt"}, 1, "swing");
}
}
$('#msg').click(function() {
$msg = $('#msg');
$msg.animate({"font-size": "80pt"}, 400, "swing");
smoothAnimation($msg, 80, 10);
$msg.animate({"font-size": "40pt"}, 400, "swing");
});
DEMO - smooth(ish) font-size animation
To make it look smoother increase the increments value to 0.25 or even 0.5. Ones you have nice smooth step you can set the points to any other value and the animation stays smooth as long as you don't force a 2 second animation interval.
Another option would be direct manipulations css transformations - here's an example (I only included webkit css to make it readable, but similar functions exist in all modern browsers). The "ease-out" property includes the fast-then-slow functionality you were aiming for. It's certainly smoother than what you've been able to get so far, but it's quite blurry - not sure if it's a trade-off you'd want to make. And as it's an experimental property, you'd still probably want your existing jQuery animation as a fallback for older browsers.
jQuery animations are terrible. Look into another tweening solution that utilizes requestAnimationFrame technique or a better timing mechanism. Maybe try a tween lib like tween.js look at the Rome demo, nice slow moving clouds...
Right now, only firefox has support for sub-pixel rendering of fonts, so animations in other browsers will always snap to pixel.

jQueryui animation with inital undefined height

See the following fiddle:
[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]
http://jsfiddle.net/NYZf8/1/ (view in different screen sizes, so that ideally the image fits inside the %-width layouted div)
The image should start the animation from the position where it correctly appears after the animation is done.
I don't understand why the first call to setMargin() sets a negative margin even though the logged height for container div and img are the very same ones, that after the jqueryui show() call set the image where I would want it (from the start on). My guess is that somehow the image height is 0/undefined after all, even though it logs fine :?
js:
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
$('img').show('blind', 1500, setMargin);
function setMargin() {
var marginTop =
( $('img').closest('div').height() - $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}
setMargin();
Interesting problem...after playing around with your code for a while (latest update), I saw that the blind animation was not actually firing in my browser (I'm testing on Chrome, and maybe it was firing but I wasn't seeing it as the image was never hidden in the first place), so I tried moving it inside the binded load function:
$('img').bind('load', function() {
...
$(this).show('blind', 500);
});
Now that it was animating, it seemed to 'snap' or 'jump' after the animation was complete, and also seemed to appear with an incorrect margin. This smacks of jQuery not being able to correctly calculate the dimensions of something that hadn't been displayed on the screen yet. On top of that, blind seems to need more explicit dimensions to operate correctly. So therein lies the problem: how to calculate elements' rendered dimensions before they've actually appeared on the screen?
One way to do this is to fade in the element whose dimensions you're trying to calculate very slightly - not enough to see yet - do some calculations, then hide it again and prep it for the appearance animation. You can achieve this with jQuery using the fadeTo function:
$('img').bind('load', function() {
$(this).fadeTo(0, 0.01, function() {
// do calculations...
}
}
You would need to work out dimensions, apply them with the css() function, blind the image in and then reset the image styles back to their original states, all thanks to a blind animation that needs these dimensions explicitly. I would also recommend using classes in the css to help you manage things a little better. Here's a detailed working example: jsfiddle working example
Not the most elegant way of doing things, but it's a start. There are a lot more easier ways to achieve seemingly better results, and I guess I just want to know why you're looking to do image blinds and explicit alignment this way? It's just a lot more challenging achieving it with the code you used...anyways, hope this helps! :)

Slideshow in Javascript without framework, animation?

The issue I am having is fairly complicated to explain. I have written up a javascript that displays an image slideshow, and it works fairly well, despite using up more resources than I would like
// imgArr[] is populated before
var i = 0;
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {
if (document.getElementById(i) != null) f();
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
}
function displaySlideshow() {
document.getElementById(destinationId).innerHTML = '<div id="slideWindow"><img src="'+imgArr[i]+'" />' + '<img src="'+imgArr[i + 1]+'" /></div>';
setTimeout('displaySlideshow()',1000*3);
i++;
if (i >= imgArr.length - 1)
i = 0;
}
loaded(destinationId,displaySlideshow);
So, this script dynamically adds two images to a HTML element, and it is wrapped in a div.
The div is styled with the height and width of the image, with the overflow (the second image) hidden.
The second image is below the first, and the slideshow is meant to go from RIGHT to LEFT.
My inquiry is twofold:
1) Is there a more efficient way of doing this?
2) How would I animate the images? Would I need to put the second image on the right of the first with CSS somehow, and then set a timer to pull the images (via a style) leftward?
I really don't recommend rolling your own animation library. The Facebook Animation Library written by the wonderful Marcel Laverdet is simple to use and comes with a lot of tutorials to get what you want out of your slideshow. (Note: ignore the FBJS stuff, it's exactly the same even if you're using it on your own site.)
If you're not using a framework, I think you'll find a lot of pain ahead of you. If you still don't want to use a framework, at least find one that is liberally licensed, and take a look at the source code. Here's one, for example.
The basic theory is, yes, you set a timer that moves the image on some sort of interval, either fixed or based on some sort of mathematical equation (eg, sin, cos, etc). By setting these intervals close together, and making lots of them, you get an "animation" in javascript. Typically, you'd use some sort of absolute positioning, moving one element off the screen as the other moves on.

Categories