5 mitos relacionados com baterias de dispositivos móveis

Todos nós nos habituámos a ouvir sugestões relacionadas com a utilização dada às baterias dossmartphones. Ainda hoje é comum ouvir a conversa da bateria que está viciada, quando simplesmente apresenta desgaste.

Mas existem outros mitos em volta das baterias e da sua utilização…

1. Não se deve utilizar o dispositivo enquanto a bateria está a carregar

Na verdade, os mitos surgem mas não são dadas grandes explicações quanto à sua possível credibilidade. Por que não utilizar o smartphone ou o tablet enquanto está a carregar?

Uma consequência dessa utilização será a de um carregamento mais lento, dependendo do tipo de tarefa que está a ser executada enquanto carrega. Outra das consequências, a que deve realmente ter algum cuidado, é do aquecimento do equipamento, já que está a ser alvo de um esforço extra. Como o calor é o maior inimigo da bateria, uma temperatura excessiva é prejudicial à bateria, não necessariamente apenas durante o período de carga.

2. Carregue sempre a bateria ao máximo!

Muitos dos mitos que ainda hoje se ouvem estão relacionados com as antigas baterias que vinham integradas nos nossos primeiros telemóveis, as baterias de níquel cádmio. Mas hoje em dia, os dispositivos estão, na sua grande maioria, equipados com baterias de iões ou polímeros de lítio, sendo muito mais modernas e com um desempenho muito mais eficiente.

Este tipo de baterias (que não vicia) tem uma vida útil que depende dos ciclos de carga, logo, quantos mais ciclos completar mais rapidamente irá degradar-se. Portanto, manter a bateria entre os 40% e os 80% será mais saudável para a vida útil da sua bateria. Mas se carregar a bateria ao máximo, ou se a deixar descarregar até níveis mais baixos (não inferiores a 10%), não irá notar, a curto prazo, perdas de autonomia significativas. Já uma descarga completa poderá inutilizar definitivamente uma bateria.

Leia também: O meu smartphone pode ficar a carregar durante toda a noite?

3. Não se pode deixar o smartphone a carregar durante toda a noite!

A verdade é que pode. Esta questão vai um pouco de encontro ao mito anterior. Se por um lado, para aumentar o tempo de vida de uma bateria, a sua carga deve oscilar entre os 40% e os 80%, por outro lado, na prática, são muito poucos os utilizadores que o fazem ou passaram a fazer. Deixar o equipamento ligado à electricidade muito tempo depois de atingir os 100% de carga não será um problema para a maioria deles.

Hoje em dia, todos os equipamentos estão preparados para que, assim que atinjam os 100% de carga, parar de receber energia, pelo que não serão alvo de sobrecarga.

No entanto, os fabricantes têm vindo a alertar para que os equipamentos que fiquem a carregar durante muitas horas seguidas não fiquem cobertos com cobertores, por exemplo, ou para que seja retirada a sua capa durante o processo, já que tendem a aquecer durante o processo de carga.

4. Não é necessário desligar nunca o seu dispositivo móvel

Já que desligá-lo poderá danificar a bateria.

Dar algum descanso à bateria ou ao próprio dispositivo não lhe fará mal nenhum. Pelo contrário. Esta acção poderá até ser benéfica para o dispositivo, já que irá “matar” algumas das acções em processo que tendem a diminuir o desempenho dos dispositivos. Pode também ajudar a que o dispositivo atinja uma temperatura mais baixa durante esse período.

5. Desligue Wi-Fi, o GPS e o Bluetooth para economizar bateria

Esta ideia pode não ser um total disparate, ou não ser propriamente um mito, dependendo do equipamento em utilização.

Em primeiro lugar, o Wi-Fi é um recurso relativamente económico, com pouca influência na autonomia. Já os dados móveis são mais consumidores de energia do que o Wi-Fi. Se está no escritório e só liga o Wi-Fi quando necessita mesmo de Internet no smartphone ou no tablet, a poupança de bateria que julga estar a fazer pode ser residual.

Quanto ao GPS, o dispositivo móvel, só o irá pedir localização quando realmente necessitar dela e, nesses casos, terá mais trabalho a ligá-lo manualmente, do que se o mantiver sempre ligado.

Os dispositivos móveis modernos já vêm todos equipados com Bluetooth 4.0, de muito baixo consumo de energia, pelo que as preocupações associadas à autonomia já não se colocam há muito.

Quais os hábitos que tem no tratamento das baterias?

Fonte: 5 mitos relacionados com baterias de dispositivos móveis

SVG Animation with GreenSock Animation Platform (GSAP)

GSAP brings vector images to life using scalable vector graphic (SVG) animations. You can animate a scene, develop HTML5 banner ads, improve project interfaces – the options are endless. My aim is to give you an introduction to GreenSock, the benefits of the platform and how to use it effectively.

To help illustrate how the platform works, I’ve embedded the development of an animation so you can see how we built it. I’ll then show you what the finished element turned out like. I’ve kept it basic on purpose but have provided links to further resources and information if you’re interested.

While you can use GSAP to animate any type of element, my focus is on using it with SVG images as there’s potential to create some awesome animations.

But first, a quick word on SVG images…

If you are unfamiliar with how SVG images and their properties, these two resources will help:

  • Jakob Jenkov has put together a great series of tutorials on his website. He is great at explaining SVG properties and including demos on how to use them.
  • Sara Soueidan writes in-depth articles on SVG for her website, making it easy to understand how it all works. She dives into the properties and provides great reference images.

On to Greensock.

Previously, you might’ve used Flash to animate for the web. But as support for Flash continues to die due to security flaws and lack of browser support, there’s a need for a worthy replacement. SVG has a range of benefits and with growingbrowser support, it makes good sense as a replacement for Flash.

One of the pain points with animating an SVG image is the inconsistencies in how browsers handle these types of images – in particular CSS transforms. Thankfully, this is where a tool such as GreenSock is handy. It solves browser inconsistencies and makes sure everything works as expected.

GSAP is a JavaScript animation library. It has a strong community, thorough documentation, large forums and plenty of demos to help educate you on how the platform works. GreenSock has multiple libraries that specialise in different areas and it’s worth browsing through the list to see what you can use.

Greensock’s performance in the browser is great. It gives you smooth transitions with the GSAP team claiming it’s “20x faster than jQuery” and “faster than CSS3 animations and transitions in many cases”.

If you want to test its performance for yourself, you can run a stress test on the GreenSock website. The test has two variables: the amount of dots animating around the screen; and the JavaScript library used to animate the dots. You can run the animation with different libraries and compare how they perform.

TweenLite is the core animation library for GSAP. It’s small and can be used alongside other GreenSock libraries. It will most likely be all you need for basic SVG animation. TweenMax is a larger library, containing Tweenlite, plus nine other GreenSock libraries. It provides a lot more functionality.

You can build a large animation without Tweenlite but you will find it hard to manage when you enter the editing phase.  This is because when you are animating elements one after another, you will need to set a duration and a delay for each element in your animation. As you tweak an element’s duration, your previously correct delays on other elements will now be too long or too short.  You’ll find yourself spending time re-tweaking delays so it still animates correctly.

GreenSock’s Timeline library comes in handy here, because it solves the above timing issues by completely removing the dependency for delays.  Each element in your stack waits for the previous elements to finish animating before it starts animating. Since the full animation runs in a cascading order you can reorder elements and change durations as you please.

Getting started

In the following examples, we will be using the TimelineMax library because it has more features. You could do these examples with TimelineLite though for a lighter weight version of the plugin.

The first thing to do is create a Timeline instance and store it as a variable. Your animations append to this new timeline. You are not restricted to only one timeline. If your animation was made up of lots of pieces you could createmultiple timelines for each piece and nest them under one master timeline.

var tl = new TimelineMax();

This line of code creates a timeline instance with a bunch of settings that are pre-configured. It’s possible to change the default behaviour, such as having the animation pause upon creation, or changing how many times the animation plays by passing in an object. To learn more about what you can do and how to do it at this point, refer to this documentation.

Animating elements in a timeline is straightforward. Below is an example of how to use the .to() method to change an element’s opacity to zero as it moves 100px on the x axis.

The tl variable we created in the previous step comes first and holds the timeline instance. Inside the to() method, the element to animate is passed in, along with the duration of the animation. After that, you can list anything you want to animate in a comma-separated list.

tl.to(element, duration, {
   x: 100,
   opacity: 0
});

Labels + timing.

Animations will be queued and played in whatever order you list them. They play one after the other, which is expected right? But what if we want to overlap animations, have a delay/pause between animations, or want to run multiple animations at the same time?

One way to achieve this is to add a string to the end of the method containing a time value.

The string will either need to include a += or -= followed by a duration. The += will add in the specified amount of time before it starts animating, creating a delay/pause effect between animations.

The -= will do the opposite, making the elements animation start early, creating an overlap effect between animations. In the first example below, the element waits 0.5 seconds before it starts animating. In the second example, the element starts animating 0.5 seconds before the first element finishes animating.

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "+=0.5");

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "-=0.5");

Another way of organising animated elements is to use labels. Labels group elements that you want to animate together in a string. You can name the label anything you choose. Elements with the same label will animate at the same time, rather than playing one after another. Labels can also be appended with += time and -= time if you want to add offsets to an element’s animation. Below are three examples of how you might implement labels in your timeline.

Example 1

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel");

Example 2

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel+=0.5");

Example 3

tl.to(element, duration, {
    x: 100,
    opacity: 0
}, "myLabel-=0.5");

Easing

Easing changes the rate of speed through an element’s animation. A linear ease will move an element at a constant speed from start to finish. An ease-out ease will start fast and slow down as the animation comes to an end. Adding the correct easing to your animations makes your animation more realistic and a lot better.

GreenSock offers a lot of easing types and offer a great visualiser tool on theirwebsite. If you want to learn more about easing and how it can be used, Ryan Brownhill wrote an article on crafting easing curves for user interfaces. It’s well worth a read and helps to further illustrate this concept.

You can also set the ease for an element’s animation. Below is an example of animating an element’s opacity and assigning a custom ease via the ease property.

tl.to(element, duration, {
    x: 100,
    opacity: 1,
    ease: SlowMo.ease.config(0.5, 0.7, false)
});

When you create a timeline instance, the setup with a default ease is Power1.easeOut. It’s possible to change the default ease with this line of code.

TimelineMax.defaultEase = add easing you want here;

Control

One of my favourite features of Timeline is that your animations are on a timeline and you can add controls. These controls pause, play, resume, reverse and restart the animation. You can build on this functionality to create some pretty cool interactive animations.

Chris Gannon, for example, created this demo to show you how you can scrub through an animation with your mouse. I also really like Adrian Parr’s demo on how to scrub through an animation using an on scroll event.

Key methods

If the information above is too dense for you, these are the fundamentals you need to get started. If nothing else, start attaching these methods to elements to see how they work. It’s also a great cheat sheet for when you’re getting started as these are methods you’ll find yourself using regularly. For an in-depth cheat sheet, check out the one Petr Tichy has put together here.

  • Set() is the equivalent of animating an element with a zero second duration. It alters an element’s appearance or position without any transition.
  • To() animates an element to a state.
  • FromTo() animates an element from one state to another state.
  • StaggerTo() animates a group of elements at the same time but with a staggered start time that you specify.
  • StagerFromTo() is a combination of the above fromTo() and staggerTo().

Helpful methods

In addition to the functionality I’ve provided in this article, I also wanted to briefly highlight three methods that I found helpful in Greensock.

  • Seek() is handy when it comes to tweaking and polishing your animation. It can be time consuming if watching the whole animation over and over. Seek takes either a time or label as its parameter. This means if you just want to view a part of your animation you can pass in a label and it will start from that point.
  • Pause() is great for inspecting what’s happening in your animation. It can be useful to chain this after a Seek call to see how things look.
  • Timescale() speeds up or slows down the overall timeline of your animation. Sometimes it can be hard to dissect an animation when it’s playing at a normal pace. Slowing it down gives you a better insight into how it’s fitting together. Timescale also comes in handy once you have built an animation and want to speed it up or slow it down without going through and tweaking the values.

The finished animation!

Putting all the above examples together, here is the finished animation I built using the tools and methods mentioned here. I encourage you to read the code and comments to see how it fits together.

View the animation on Codepen and play around with it in your browser. Don’t be scared of breaking it – go ahead and edit the code, tweak values and re-order events. Experimenting with the animation will improve your understanding of how it works. If you have any questions, feel free to add them to the comments below – I’m more than happy to try and help you out if I can.

Further resources

If you can’t get enough of GreenSock and want to read more about animating SVG images with it. Check out these links for more information.

Wrapping up

This article is meant to be an introduction to GSAP. I hope you’ve found it useful. Take these foundation ideas and create something simple or make it as intricate as you want. I’ve mentioned in a previous article that Codepen is a great source of inspiration and this is definitely the case for animations.

Here are some of my favourite GSAP animations. I recommend viewing the animations and reading the source code to see how different people create them. Viewing animations at a slower pace will help you get a better look at how it moves and fits together. As I mentioned earlier in the article, we can apply aTimescale to the timeline to slow it down.

After viewing the demos and learning how to animate using GreenSock, I hope you’re inspired to go off and make something of your own.

Post a link to your work in the comments, I’d love to see it. If you are thinking “I want to make something but I can’t think of anything to make”, check out theCodepen Creative Challenge.

It’s a growing community where users create pens around a theme. There are no prizes – it’s all for the fun of it. But it’s a great way to get inspired and to build something, share knowledge and be part of a community. It’s super-cool to see what others come up with.

Happy animating!

Allan gives us a run down of the GreenSock Animation platform and create an awesome animation for this blog article in the process. Check it out!

 

Fonte: SVG Animation with GreenSock Animation Platform (GSAP) | August

Want to learn JavaScript in 2015?

Uma excelente história de Vincent O que durante um ano, focou-se a aprender Javascript, e hoje trabalha nessa área.

Para contar esta história, Vincent utilizou o serviço Medium, website onde podemos contar as nossas histórias num layout simples e amigável.

This is a walk-through of the steps I personally took in a single year, to begin learning JavaScript. My goal was to be able to get a job…

Fonte: Want to learn JavaScript in 2015? — Medium

Tinderesque – building a Tinder-like interface with CSS animations and vanilla JS #justcode

Tinder is a very successful dating app, and one of its features is a way to say yes or no to prospective partners by swiping right or left or pressing a yes or no button. The interface is cards that drop when you press the buttons.

As with any successful interface, a lot of clones that mimick them happen very fast. One of those is FontFlame – a Tinder for Font Pairings. When I saw this one, I thought the animation isn’t right (it just moves to the right or left and fades, there’s no turning or popping up). I tried to fix the CSS animation to match more closely what Tinder is doing, but to my dismay I found out that whilst Fontflame uses CSS animations, they get over-ridden by jQuery ones. I contacted the author and offered my CSS animation to replace the current one.

Just for fun, I packed this up into a quick solution consisting of a CSS animation and some JavaScript to control the voting process.

I called it Tinderesque. You can see it in action, Get the code and read the instructionshow to use it on GitHub.

Here’s some explanations on how Tinderesque works.

THE TINDERESQUE ANIMATION

Animating the cards is no rocket science: we rotate the card after setting the transformation origin to the bottom of the card and shift it up a bit to get a “discard” effect.

First up, we need to define the HTML of the collection of cards we want to vote on. This should be pretty straight forward:

html

To achieve the animation effect we need to give the card we want to animate some dimensions and set its transform origin to its bottom:
.card {
  width: 150px;
  height: 200px;
  display: block;
  background: #666;
  transform-origin: 50% 99%;
}

This ensures that the card doesn’t get rotated around its centre but the bottom instead.

For the positive scenario, we rotate the card clockwise and push it up a bit to get the discard effect. This can be done using a rotate and translateY transformation. We also animate the opacity of the card from 1 to 0, effectively hiding it.

@keyframes yay {
  from {
    transform: rotate(0deg);
    opacity: 1;
  }
  to {
    transform: rotate(40deg) translateY(-80px);
    opacity: 0;
  }
}

For the negative use case, we rotate the card counter-clockwise:

@keyframes nope {
  from {
    transform: rotate(0deg);
    opacity: 1;
  }
  to {
    transform: rotate(-40deg) translateY(-80px);
    opacity: 0;
  }
}

We then trigger these animations by adding and removing classes on the parent elmement of the cards:

.cardcontainer.yes .card {
  animation: yay 0.7s ease-out;
}
.cardcontainer.nope .card {
  animation: nope 0.7s ease-out;
}

GOING THROUGH THE WHOLE CARD DECK

In order to go through the card deck two things must happen:

  • We need to animate the current card using the positive or negative animation
  • When the animation is finished, we need to remove the card from the document and show the next one.

By default, we hide all the cards in the deck. Only the one with the class of current is visible:

.list .card {
  display: none;
}
.list .current {
  display: block;
}

This means that we need to shift the class of current to the next card once this one has been approved or discared. But first, we need to trigger the animation. In order to achieve this, we need either a hover or some clever trickery with checkboxes in CSS. It is more extensible though to use JavaScript.

TRIGGERING THE ANIMATIONS

All we need to trigger the animations is adding an event handler attached to the buttons in the HTML. Depending on which button was pressed we add a yes or nope class to the parent element of the button – in this case, the cardcontainer DIV.

function animatecard(ev) {
  var t = ev.target;
  if (t.className === 'but-nope') {
    t.parentNode.classList.add('nope');
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
  }
}
document.body.addEventListener('click', animatecard);

We’re using event delegation here with a click handler on the body of the document. We can of course extend this to pointer or touch handlers to allow for touch events and simulating swipe gestures.

ACTING AFTER THE ANIMATION USING EVENTS

Our card has now been animated and is invisible, but it is still in the document and the next card isn’t visible yet. We need to remove the card and shift the current class to the next card in the deck.

Every CSS animation has an animationend event we can use for that. The event gives us the name of the event, which gives us the name of the class to remove.

function animationdone(ev) {
 
  // get the container
  var origin = ev.target.parentNode;
 
  // remove the appropriate class
  // depending on the animation name
  if (ev.animationName === 'yay') {
    origin.classList.remove('yes');
  }
  if (ev.animationName === 'nope') {
    origin.classList.remove('nope');
  }
 
  // if any of the card events have 
  // ended…
  if (ev.animationName === 'nope' ||
      ev.animationName === 'yay') {
 
  // remove the first card in the element
    origin.querySelector('.current').remove();
 
  // if there are no cards left, do nothing
    if (!origin.querySelector('.card')) {
      // no more cards left - 
      // TODO other functionality
    } else {
 
  // otherwise shift the 'current' class to 
  // the next card 
      origin.querySelector('.card').
        classList.add('current');
    }
  }
}
document.body.addEventListener(
  'animationend', animationdone
);

That’s more or less all we need to do. Except that Safari still hasn’t joined us in the year 2015. That’s why we need to repeat both the CSS animation definitions in our CSS with –webkit– prefixes and add an event handler for webkitAnimationEnd. I refuse to do so here, as this is depressing, but you can see it in the tinderesque source code.

EXTENDING THE FUNCTIONALITY USING CUSTOM EVENTS

The functionality now is pretty basic, which means we want to make it as easy as possible to extend it. The simplest way to do that is to add Custom Events that fire when things happen to our card deck. This is as easy as using this function:

function fireCustomEvent(name, payload) {
  var newevent = new CustomEvent(name, {
    detail: payload
  });
  document.body.dispatchEvent(newevent);
}

Custom events can get a payload – you can define what the listener gets as parameters. In the case of tinderesque, the animatecard function has been extended to send a reference to the button that was clicked, its container element (in case you have several decks) and a copy of the current card.

function animatecard(ev) {
  var t = ev.target;
  if (t.className === 'but-nope') {
    t.parentNode.classList.add('nope');
    fireCustomEvent('nopecard',
      {
        origin: t,
        container: t.parentNode,
        card: t.parentNode.querySelector('.card')
      }
    );
  }
  if (t.className === 'but-yay') {
    t.parentNode.classList.add('yes');
    fireCustomEvent('yepcard',
      {
        origin: t,
        container: t.parentNode,
        card: t.parentNode.querySelector('.card')
      }
    );
  }
}

This allows you to read the content of the card before it gets removed from the document.

var b = document.body;
b.addEventListener('nopecard', function(ev) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});
b.addEventListener('yepcard', function(ev) {
  console.log(
    ev.detail.card,
    ev.detail.card.innerHTML
  );
});

Tinderesque also fires a custom event called deckempty when the last card got removed from the list. In the demo page this is used to re-stack the deck:

var b = document.body;
b.addEventListener('deckempty', function(ev) {
  var container = ev.detail.container;
  var list = container.querySelector('.cardlist');
  var out = '<li class="card current">#1</li>';
  for (var i = 2; i < 6; i++) {
    out += '<li class="card">#' + i + '</li>';
  }
  list.innerHTML = out;
});

This should get you well on the way to build your own Tinder-like interface. If I find the time, I will record a screencast doing exactly that.

CUTER – A QUICK DEMO USING TINDERESQUE

As a demo, I put together Cuter – a way to say yes or no to cute animal pictures and end up with a list of the ones you chose.
You can see it on YouTube:

https://www.youtube-nocookie.com/embed/6kvDBUTPV74?rel=0

Fonte: Tinderesque – building a Tinder-like interface with CSS animations and vanilla JS #justcode | Christian Heilmann