Make lines blink inside a canvas - javascript

I'm currently working on a HTML5 and Javascript project using Kinetic Js and canvas.
I need my lines (Kinetic.Line) to blink.
I've tried something consisting of an infinite loop with setTimeout function inside, but I can't use javascript then (such a drawback because then I can't select points!).
Does somebody have an idea that can help me?
while (1) {
setTimeout("stage.load(myjson[0])", 1000);
setTimeout("stage.load(myjson[1])", 1000);
}
(sorry for my poor english)

Here's one way of making a line blink using KineticJS. Rather than using setTimeout, I think it's better to use the KineticJS onFrame event which is built into the stage object. You can then use setAlpha to set the opacity of the line, and getAlpha to get the current opacity of the line. setAlpha('0') will make the line transparent, setAlpha('1') will make the line visible.
I've set up a fiddle here:
JSFiddle
Here's the relevant bit that actually flashes the line:
var flashTime = 0;
stage.onFrame(function(frame){
if(frame.time > (flashTime + 250)){;
flashTime = frame.time;
redLine.setAlpha(redLine.getAlpha() == 1 ? '0' : '1');
layer.draw();
};
});

Related

Problem synchronizing DOM manipulation with style changes in carousel

I built a basic picture carousel a while back, and I'm finally getting around to transferring it from MooTools over to jQuery so I can drop MooTools. I've got the script completely functional, but for whatever reason when the carousel slides in one direction, you can see a "pop" where it resets itself.
I've tried playing around with the order it handles everything, but no matter what it seems to always desync for just a fraction of a section.
Here's a copy of my code: https://jsfiddle.net/Chaosxmk/pf6dzchm/
The offending section of code is this:
styles['position'] = 'absolute';
styles[self.params.axis] = -32768;
$(self.list[0]).css(styles).hide();
$(self.list[0]).appendTo(self.carousel);
$(self.list[conf.mi]).css(self.params.axis, (100-conf.pr)+'%');
styles = {};
styles['position'] = 'relative';
styles[self.params.axis] = 'auto';
$(self.list[conf.mi]).css(styles);
Issue is that $.fadeOut() sets display:none on the element, which causes some strange rendering issues in your setTimeout() callback. Works better if you use $.fadeTo() instead:
if (self.params.direction) {
// Go forward
self.carousel.css(self.params.axis, '-'+conf.pr+'%');
$(self.list[0]).fadeTo(400, 0);
$(self.list[conf.mi]).css(self.params.axis, '100%').fadeTo(400, 1);
} else {
// Go backward
self.carousel.css(self.params.axis, conf.pr+'%');
$(self.list[conf.mi-1]).fadeTo(400, 0);
self.list.last().css(self.params.axis, '-'+conf.pr+'%').fadeTo(400, 1);
}
For simplicity I used a 400ms duration, but you can set this to whatever you need.
JSFiddle

Refresh DIV before heavy computation

This keeps bugging me and although there's a lot of "Refresh DIV with jQuery" questions out there, none addresses (haven't found it, that is) this simple matter : how do I refresh (visual aspect) a DIV before doing some heavy lifting calculations? The idea is simple, I'm creating a big chart with D3 that takes a couple of seconds to generate and I want to be able to put an animated gif in overlay before computation and remove it after. Something like :
$("#test").empty();
$("#test").text("Should be seen while waiting");
for (var i=1;i<2000000000;i++) {
//Draw heavy SVG in #test that takes time
}
$("#test").empty();
$("#test").text("Ready");
$("#test").css("color", "red");
Simple, but I haven't been able to do it thus far : the "Should be seen while waiting" never appears :(
A simple Fiddle here demonstrates the behaviour : http://jsfiddle.net/StephMatte/q29Gy/
I tried using setTimeout and jQuery's .delay() in 3 different browsers, but to no avail.
Thanx for any input.
Try this-
box = $("<div>", {'id': 'box'});
$("#test").append(box);
$("#box").text("Should be seen while waiting");
for (var i=1;i<2000000000;i++) {
//Draw heavy SVG in #test that takes time
}
$("#box").remove();
$("#test").text("Ready");
$("#test").css("color", "red");`
It turns out I was simply using the wrong syntax with setTimeout().
This did the trick :
$("#test").text("Is seen while generating heavy SVG");
setTimeout(function(){build_chart();}, 100);
$("#test").empty();
10ms wasn't enough, but 100ms is enough for the DIV to show its new content before going into heay computation.

What is the cleanest way to animate without .animate() jQuery?

I had a nice idea, namely to use the 'stroke-dasharray' CSS-attribute that can be used on SVG objects, to stroke the paths on the page, giving it a nice artistic way for shapes to appear.
It works perfectly and is supported by most modern browsers as well as phones.
A nice jsfiddle of what I've made can be found here: http://jsfiddle.net/G6ECE/
The code that makes the whole thing tick right now:
num=0;
setInterval(function(){
updateStroke(num);
num+= 0.2;
}, 1);
function updateStroke(num){
// stroke-dasharray is a list of two or more numbers. In this example, percentage values are used to make all paths fully stroked at the end of the animation, irregardless of path length.
$('svg path').css({stroke:'#00FF00','stroke-dasharray':num+'% '+(100-num)+'%'});
}
Obviously this is a very basic, ugly way to animate something.
I want to customize the animation a little: I want to be able to add a custom animation length and also use different easings. Unfortunately, the jQuery $().animate() function that I'd normally use to animate CSS attributes, does not support non-numeric values.
As stroke-dasharray uses two or more numeric(pixel or percentage) values to work, I need an alternative for .animate()
What would be the cleanest way to do this? (with using as much existing jQuery functionality as possible, and as little as possible re-inventing an animation framework)
What about CSS transitions? They also have a better performance than jQuery animations.
http://www.w3schools.com/css/css3_transitions.asp
But be sure not to use both for the same property as jQuery animations interfere with CSS transitions.
Recently, I have been working with a nice robust cross-browser javascript animation object. Once you understand the way it is used, it becomes quite seamless for all or your SVG animations. It can be attached to any svg element and control associated values.
There are some examples that show the various choices of animation performance(linear, quadratic, ease,etc) at:
http://www.svgDiscovery.com/
Below is the object:
var AnimateJS=function(options){
this.options=options
var start = new Date
var iT = setInterval(
function(){
var timePassed = new Date - start
var progress = timePassed / options.duration
if (progress > 1) progress = 1
this.progress=progress
var delta = options.delta(progress)
options.output(delta)
if (progress == 1)clearInterval(iT);
},options.delay)
}

Improving Performance on Background Parallax Scrolling

Hello StackOverflow Community,
what I am trying to achieve is a header that can be moved with the mouse.
You klick into the header and drag the mouse and the elements inside the header will move with different speeds.
I achieved the parallaxing part but the performance is not really good. It is partially a bit laggy while dragging the backgrounds.
My question now is: what can be changed in the code to get a performance boost?
That's the part of the code that takes care of parallaxing. On every mousemove a each loop is executed which I think is the reason for the performance beeing so laggy:
var dragging = false;
var clickMouseX;
//Our object for the layers
//each layer has a different scrolling speed
var movingObjects = {
'#header-l1' : {'speed': 1},
'#header-l2' : {'speed': 1.4},
'#header-l3' : {'speed': 1.85},
'#header-l4' : {'speed': 2.2},
};
$('#header-wrapper').mousedown(function(e){
dragging = true;
//Get initial mouse position when clicked
clickMouseX = e.pageX;
$(this).mousemove(function(mme){
//execute only if mousedown
if(dragging){
//iterate through all layers which have to be parallaxed
$.each(movingObjects, function(el, opt){
var element = $(el);
//get difference of initial mouse position and current mouse position
var diff = clickMouseX - mme.pageX;
//scroll-position left speed 1
if(diff < 0) diff = -1;
//scroll position right speed 1
if(diff >= 0) diff = 1;
//get current position of layer
currLeft = parseInt(element.css('left'));
//get current layer width
elWidth = element.width();
//if right border is reached don't scroll further
if(currLeft < -(elWidth - 810)){
element.css('left', -(elWidth - 810));
}
//so do with left border
if(currLeft > 0){
element.css('left', 0);
}
//parallax it! Subtract the scroll position speed multiplied by the speed of the desired
//layer from the current left property
element.css('left', parseInt(element.css('left')) - diff*opt.speed);
});
}
});
/* Cursor */
$(this).css('cursor', 'pointer');
return false;
});
I also put a fiddle up:
http://jsfiddle.net/yWGDz/
Thanks in advance,
Thomas
P.S. maybe someone even finds out why layer two and three have the same scroll speed while having different speeds defined.
I worked at this a bit, and came up with this: http://jsfiddle.net/amqER/2/
This works a lot faster than the original (especially in firefox, where it performs a whole lot better, chrome it's still pretty slow). I also changed up some of the logic in your code, to make it make more sense.
A list of things that I did:
Minify your pngs
2 of your png files were over 2 megs, so I threw them into a png compressor (tinypng) and that reduced the size a lot. This helps with loading time and overall snappiness.
Re-use values as much as possible
In your original code, you wrote to and then subsequently read from the css left property a couple times in your code. Doing this is going to make it a lot slower. Instead, I kept an left property, and would only touch $.css when I absolutely needed to. Likewise for reading each element's width each update.
Also, like I said, I modified your logic to (I think) make more sense, given what you were trying to accomplish. It calculates a new diff each update, and tries to move according to that. Also, it doesn't try to keep moving once one of the images falls off (which yours does if you move all the way to the right, and it looks really weird). You can also look at this: http://jsfiddle.net/amqER/5/, which maybe is more like the control scheme you wanted.
Just some quick performance tips.
Try not to use $(this).mousemove instead save $(this) into a variable and use that.
var th = $(this);
th.mousemove...
Try to avoid using $.each. This is probably the part that's slowing your code down.
You can replace it with a for loop, but I would suggest, in this case, sending in each element one by one.
var parallax = function(img){
};
parallax(img1);
parallax(img2);
instantly-increase-your-jquery-performance
Whilst Xymostech's answer does greatly improve upon the original poster's original code; the performance is hardly improved for me in Chrome.
Whilst inspecting the page FPS, the solution posted here runs at 15FPS for me on a Retina MacBook Pro.
I made a very simple change to the code, altering it to use translate3d properties instead of left. Now, it runs at 55-60 FPS for me. I'd call that a massive performance boost.
If 'show paint rectangles' are turned on in Chrome, you'll see the previously posted solution is continually painting changes to the dom whilst the parallax is in motion. With the translate3d solution, there's simply zero painting done the whole time the parallax is in motion.
http://jsfiddle.net/LG47e/

Fx on JavaScript: How to fade stuff, etc without frameworks?

I would like to learn how to do fade, and similar effects on JavaScript. I often get answers, like why not use jQuery, Mootools, etc ? Well, I want to learn how stuff works, then I won't mind using any of these frameworks.
I'm currently learning about making changes on the DOM, so, I've read a lot of stuff on this theme. Also, I've read about Reflow, still, I didn't find any cool stuff on Repaint, but, I'll keep searching.
From seeing source files etc, I see a few methods, that I don't know if they've created or are Core methods of JS.
My question is, is there any resource where I can learn all this neat stuff like smooth position change, fading elements trough opacity or whatever, etc?
Take a look at emile.js. It's brand-spanking new. Great way to learn how to do your own.
Introduced at the recent jsconf conference. Written by Thomas Fuchs (script.aculo.us).
http://github.com/madrobby/emile
Émile Stand-alone CSS animation
JavaScript mini-framework
Doesn't need
a JavaScript framework
Full set of CSS
properties for animation (length-based
and colors)
Easing and callbacks
Less
than 50 lines of code
Get updates on
Twitter: http://twitter.com/emilejs
here's an example that works in firefox and chrome. ie doesn't respect the opacity style.
var ELEMENT;
var STEPS;
var INTERVAL;
var COUNT;
var TIMERID;
// 5 * 200ms = 1 second
STEPS = 5;
INTERVAL = 200;
function Button1_onclick() {
ELEMENT = document.getElementById("foo");
COUNT = STEPS - 1;
TIMERID = setInterval(Fade, INTERVAL);
}
function Fade() {
ELEMENT.style.opacity = String(COUNT / STEPS);
COUNT--;
if (COUNT < 0) {
clearInterval(TIMERID);
TIMERID = 0;
}
}
setInterval and clearInterval are standard js functions. they will execute the given function every x milliseconds. in our case we kill it when we've hit 0 opacity.
sliding a window is a similar process. you'd set the left/right/top/bottom style instead of opacity.
Fading using javascript is basically modifying opacity of an element programmatically. The "smoothness" is done by using timers. Same for position/size changes. You need to read up on css to understand what style properties of an element you have to control using javascript for the effect you want.
If you are really curious, you can dive into the source of yui in github: http://github.com/yui

Categories

Resources