Tag Archiv: learn
Getting Started With The JavaScript Web Animation API
Adding animations to web interfaces makes pages and apps feel more responsive and interactive. A side menu that smoothly slides out of view provides a much better user experience then a menu that just disappears when you close it.
So far creating web animations was done either via CSS transitions, CSS keyframes, or an external library such as Animate.css or Velocity. Thanks to a new native JavaScript API, we are now able to freely animate any HTML element without ever having to leave our .js file.
Creating Animations
To showcase the awesomeness of the new API, let’s build a super simple example, once the old-fashioned CSS way, then with JavaScript Web Animations.
The editor below contains two HTML divs that when clicked on move to the right and then change their color. The square is animated via CSS @keyframes
, and the circle via the Web Animations API.
(Play with our code editor on Tutorialzine.com)
The @keyframes
animation should be familiar to most developers so let’s look at that first.
The CSS Approach
Our CSS animation is defined in a @keyframes
block that represents a timeline of all the transitions. Once we have our choreography defined, we can map it to a selector via the animation property and it’s options.
.animate { animation-name: move-and-change-color; animation-duration: 0.4s; animation-fill-mode: forwards; } @keyframes move-and-change-color { 0% { transform: translateX(0); } 80% { transform: translateX(100px); background-color: #2196F3; } 100% { transform: translateX(100px); background-color: #EF5350; } }
We want the animation to start on user interaction so we will also have to create an on-click event listener that adds a CSS class to the desired element:
var square = document.getElementById('square'); square.addEventListener('click', function() { square.className += " animate"; });
Although it works pretty well, the CSS approach seems rather non-intuitive as we define what happens in the stylesheets, but actually start it in the JavaScript. We also have very limited control over the animation once it has been invoked. Both these problems can be solved by switching to the Web Animation API.
The JavaScript Approach
We can describe our JavaScript animation using almost the exact same transitions we used in the CSS example:
var moveAndChangeColor = [ { transform: 'translateX(0)', background: '#2196F3' // blue }, { offset: 0.8, transform: 'translateX(100px)', background: '#2196F3' // blue }, { transform: 'translateX(100px)', background: '#EF5350' // red } ];
Each object in the array represents a state of the animation. The states are evenly distributed in time (3 states – 0%, 50%, 100%) unless we change the timing using the offset
option, as we’ve done with the middle state.
After we’ve defined our animation array, we can invoke it using the animate() method. It takes as a second argument an object with the same options as the CSS animation property, although with slightly different names (e.g. animation-fill-mode
is fill
, animation-iteration-count
is iteration
, etc).
var circle = document.getElementById('circle'); circle.addEventListener('click', function() { circle.animate(moveAndChangeColor, { duration: 400, fill: 'forwards' }); });
As you can see, the JavaScript approach is much more organized with the animation stored in a variable and the animate()
method used for invoking it whenever we need to.
Controlling Animations
The Web Animation API also makes it possible to easily control the playback of an animation in a number of ways. The animate()
method returns an Animation object which we can save in a variable and use to refer to that animation later on.
var animation = elem.animate(transitions, options);
The interface provides us with the following methods:
- pause() – Freezes the animation in its current state.
- play() – Resumes the animation or restarts it if it has finished.
- reverse() – Plays the transitions backwards.
- finish() – Goes to the end of the animation (or the beginning if reversed).
- cancel() – Stops playback and returns to starting state.
Below is a tiny demo with a loading indicator that loops infinitely. We’ve setup buttons for the different events so that you can try them out:
(Play with our code editor on Tutorialzine.com)
Properties and Events Listeners
The Animation object returned from animate()
holds several useful properties that give us access to options like the current time, the playback rate, and others. Although some are read-only, most of the properties can be used as setters and getters.
You can view the JS code in the editor below to get a sense of how they work. For the full list of properties visit MDN.
(Play with our code editor on Tutorialzine.com)
In addition to that, the Web Animation API provides us with two useful event handlers for when the animation has finished or has been canceled:
spinnerAnimation.addEventListener('finish', function() { // Animation has completed or .finish() has been called. doSomething(); }); spinnerAnimation.addEventListener('cancel', function() { // Animation has been canceled. doSomething(); });
Support and Performance
Most of the Web Animation features are freely available in Chrome and Firefox, with Edge and Safari implementations in the working (caniuse). There is also a well maintained open-source polyfill which can be used while waiting for full browser coverage.
When it comes to performance, there shouldn’t be any difference compared to regular CSS transitions, as browsers use the same engine for both. If you stick to animating only properties that don’t cause redraws, such as transform
and opacity
, animations should keep a steady 60fps rate.
Conclusion
The Web Animation API gives developers an awesome new way to create and control web animations using nothing but pure JavaScript. For animations that are invoked on user interaction or other dynamic events, this is great news since the whole animation can be done in the controller code, without having to jump to a CSS file for the actual transitions.
This article covered most of the features of the new API, but if you want to learn more here are a couple of excellent resources we highly recommend:
- Using the Web Animations API on MDN
- Animatelo – A rework of Animate.css using the Web Animation API
- Let’s talk about the Web Animations API – A 5-part tutorial by Daniel C. Wilson
5 Beautiful Image Effects With CSS Shapes and Filters
A visual web experiment in which we create majestic polyscape backgrounds using nothing but CSS and HTML.5 Beautiful Image Effects With CSS Shapes and Filters
Today we’ve prepared for you five background images showcasing the power of modern CSS. They can be used as desktop wallpapers, eye-catching landing pages, and even as printed posters. In the article below we’ll also go over some of the key CSS techniques, so that you can customize them to your liking or make your own ones from scratch.
The Designs
A Polyscape (poly = many, scape = scenery) is an image that contains multiple pictures mixed into one, creating very pleasing surrealistic visuals. Usually such design are made in Photoshop or other image editing software, but thanks to the ever growing arsenal of CSS properties, awesome polyscapes can now be created using nothing but simple web technologies!
You can view the designs in a demo app we created. The full source code plus all the polyscapes exported into HD images can be downloaded as a .zip archive from the Download button near the top of this page.
The demo uses some experimental CSS properties which might not work in all browsers. For the full experience, it’s best to open it in Chrome.
Making these polyscapes was very easy and we had a lot of fun in the process. For the backgrounds we used images from Unsplash. Everything else is done via various CSS shapes, transforms, and filters.
CSS Shapes
The designs use a variety of geometrical shapes made out of CSS. Here is how they are done:
- Squares – HTML blocks are rectangular by default. Just choose
height
andwidth
. To turn them sideways we usetransform: rotate(45deg);
. - Circles – Circular shapes in CSS can be created by adding
border-radius: 50%;
to a square shape. - Triangles and Diamonds – Possible thanks to
clip-path
. We’ve recently wrote about this in detail in our article CSS Triangles Without Ugly Hacks. Check it out!
Another interesting CSS shape we wanted to make is a square that is transparent inside but has an image as its border:
It turns out there is a CSS spec that does exactly that – it’s called border-image
and takes as parameters the path to an image, the border size, and how to place the image.
background: transparent; border: 25px solid transparent; border-image: url(clouds.jpg) 25 stretch;
CSS Filters
Since we are adding images on top of an image background, in many cases we need to apply some filters to make the two views stand out. Most modern browsers freely support this feature under the filter
property.
It allows us to shift the hue from one color to another, boost the contrast, make everything black-and-white, and others. Here is a list of all the available CSS filters:
- grayscale
- hue-rotate
- invert
- contrast
- blur
- brightness
- opacity
- saturate
- sepia
- drop-shadow
We can combine as many filters as we like until we get the desired result:
filter: hue-rotate(60deg) contrast(200%) blur(2px);
Conclusion
We hope you’ve enjoyed our little CSS experiment. The demo and all of the code is 100% free, and you have all rights to use, share, and change the designs (our license).
15 Interesting JavaScript and CSS Libraries for May 2017
Our monthly compilation of web dev resources is here and it is packed with awesome frameworks, plugins, and other useful freebies.15 Interesting JavaScript and CSS Libraries for May 2017
Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.
Buefy
Ligthweight UI framework for Vue.js built using the popular flexbox-based CSS library Bulma. It has all the components a typical web app needs inluding dynamic elements like modals, toasts, and notifications, enableing devs to quickly add any user interface to their existing Vue.js projects.
HR.js
Zero-dependency library for programatically highlighting and replacing strings within the DOM. The HR.js API couldn’t be simpler – just use a CSS selector to target the parent HTML element holding the desired text, choose which words to highlight, set the background color, and you’re done!
React VR
React VR is a framework for the creation of VR applications that run in your web browser. It pairs modern APIs like WebGL and WebVR with the declarative power of React, producing experiences that can be consumed through a variety of devices.
Tippy.js
Pure JavaScript library for animated tooltips. It provides a wide range of different on-hover effects and a ton of customization with over 20 options. Tippy.js is super ligthweight and has rather good browser compatibility, automatically falling back to regular title
attributes when not supported.
Barba.js
Dependancy-free JavaScript library for creating smooth transtitions between the views of your single page apps. The logic is built around PJAX (push state AJAX) which checks all valid URLs, prevents their normal behavior and instead loads the new page via a XMLHttpRequest. Barba also makes sure the change in state is properly reflected in your app’s URL via the Push State API.
UIkit
Excellent CSS and JavaScript front-end framework, including its own SVG icon font and dozens of components. UIkit is designed very well, both in looks and as a framework, with unified styles, easy to remember API, many customization options, and useful modifyer classes. The docmentation is also top-notch.
Haul
Haul is a command line tool for developing React Native apps. It can be used as a direct replacement of the React Native packager, providing better webpack support, improved error messages, and greatly reduced compilation times. Haul is well documented, customizable, and completely open-source.
AcrossTabs
JavaScript library for communicationg between cross-origin browser tabs, making it possible for one web page to open and close additional browser tabs. The parent tab has access to useful information about its children tabs, including unique ids and whether the child tab is still open or has been closed.
Stylelint
Stylelint is a modern CSS linter that will help teams eforce unopinionated CSS standards in their stylesheets. The library is pretty powerful and can forbid or whitelist specific properties, catch errors, and recognize SCSS syntax. Stylelint is totaly cusotmizable, giving you the option to add new rules or opt-out of those that you don’t agree with.
Iconate
Awesome vanilla JavaScript library that allows you to transform one icon to another on click, with a variety of smooth animations. Iconate works with all CSS icon fonts – just add an icon to your HTML and use the simple JavaScript API to choose what to transform it into and which of the 15+ animations to use.
React-Datasheet
React component that can be used for adding fully functional Excel-like datasheets to your apps. Table cells can be freely edited, group-selected, copied, pasted, deleted, and everything else you’d expect, with keyboard navigation also available. There are 3 useful examples on their GitHub – a basic table, spreasheet with formulas, and table with nested components.
Pure CSS
Modular CSS framework with a minimal footprint. The entire library is just 3.8 kb minified and gzipped but this size can be further reduced by excluding the parts you don’t need. Modules include a base set of styles, a responsive grid, form components, buttons, tables, and menus.
Simple Icons
Huge collection of free icons for popular social networks, apps, services, and other brands. Since all the icons are made with SVG they can be scaled to any size without fear of pixelation or smudges. Being SVG-based also makes them super lightweight – most are under 500 bytes, more detailed ones around 1 or 2 KB.
Chroma.js
Tiny JavaScript library for working with colors. It offers a rich API with over 50 functions for manipulating colors, letting you swtich between color modes, change brightness and saturation, create gradient scales, and many other useful methods.
Weex
Weex is a framework for building cross-platform mobile apps, similar to Reat Native but for Vue.js. It allows you to write your app in HTML, CSS, and JavaScript, which then will be rendered in Java for Android and Swift for iOS. The framework has a number of built-in components, APIs, and other helpful utilites.
10 Machine Learning Examples in JavaScript
A collection of cool libraries and web experiments that will help JavaScript developers make their first steps in machine learning.10 Machine Learning Examples in JavaScript
Machine learning libraries are becoming faster and more accessible with each passing year, showing no signs of slowing down. While traditionally Python has been the go-to language for machine learning, nowadays neural networks can run in any language, including JavaScript!
The web ecosystem has made a lot of progress in recent times and although JavaScript and Node.js are still less performant than Python and Java, they are now powerful enough to handle many machine learning problems. Web languages also have the advantage of being super accessible – all you need to run a JavaScript ML project is your web browser.
Most JavaScript machine learning libraries are fairly new and still in development, but they do exist and are ready for you to try them. In this article we will look at some of these libraries, as well as a number of cool AI web app examples to get you started.
1. Brain
Brain is a library that lets you easily create neural networks and then train them based on input/output data. Since training takes up a lot of resources, it is preferred to run the library in a Node.js environment, although a CDN browser version can also be loaded directly onto a web page. There is a tiny demo on their website that can be trained to recognize color contrast.
Deep playground
Educational web app that lets you play around with neural networks and explore their different components. It has a nice UI that allows you to control the input data, number of neurons, which algorithm to use, and various other metrics that will be reflected on the end result. There is also a lot to learn from the app behind the scenes – the code is open-source and uses a custom machine learning library that is written in TypeScript and well documented.
FlappyLearning
FlappyLearning is a JavaScript project that in roughly 800 lines of unminifed code manages to create a machine learning library and implement it in a fun demo that learns to play Flappy Bird like a virtuoso. The AI technique used in this library is called Neuroevolution and applies algorithms inspired by nervous systems found in nature, dynamically learning from each iteration’s success or failure. The demo is super easy to run – just open index.html in the browser.
Synaptic
Probably the most actively maintained project on this list, Synaptic is a Node.js and browser library that is architecture-agnostic, allowing developers to build any type of neural network they want. It has a few built-in architectures, making it possible to quickly test and compare different machine learning algorithms. It’s also features a well written introduction to neural networks, a number of practical demos, and many other great tutorials demystifying how machine learning works.
Land Lines
Land Lines is an interesting Chrome Web experiment that finds satellite images of Earth, similar to doodles made by the user. The app makes no server calls: it works entirely in the browser and thanks to clever usage of machine learning and WebGL has great performance even on mobile devices. You can check out the source code on GitHub or read the full case study here.
ConvNetJS
Although it is no longer actively maintained, ConvNetJS is one of the most advanced deep learning libraries for JavaScript. Originally developed in Stanford University, ConvNetJS became quite popular on GitHub, resulting in many community driven features and tutorials. It works directly in the browser, supports multiple learning techniques, and is rather low-level, making it suitable for people with bigger experience in neural networks.
Thing Translator
Thing Translator is a web experiment that allows your phone to recognize real-life objects and name them in different languages. The app is built entirely on web technologies and utilizes two machine learning APIs by Google – Cloud Vision for image recognition and Translate API for natural language translations.
Neurojs
Framework for building AI systems based on reinforcement learning. Sadly the open-source project doesn’t have a proper documentation but one of the demos, a self-driving car experiment, has a great description of the different parts that make up a neural network. The library is in pure JavaScript and made using modern tools like webpack and babel.
Machine_learning
Another library that allows us to set up and train neural networks using only JavaScript. It is super easy to install both in Node.js and in the client side, and has a very clean API that will be comfortable for developers of all skill levels. The library provides a lot of examples that implement popular algorithms, helping you understand core machine learning principals.
DeepForge
DeepForge is a user-friendly development environment for working with deep learning. It allows you to to design neural networks using а simple graphical interface, supports training models on remote machines, and has built in version control. The project runs in the browser and is based on Node.js and MongoDB, making the installation process very familiar to most web devs.
Bonus: Machine Learning in Javascript
An excellent series of blog posts by Burak Kanber that goes over some of the machine learning fundamentals. The tutorials are well written, clear, and targeted specifically towards JavaScript developers. A great resource if you want to understand machine learning more in depth.
Conclusion
Although the JavaScript machine learning ecosystem is not fully developed yet, we recommend using the resources on this list to make your first steps in ML and get a feel for the core techniques. As the experiments in the article show, there are tons of fun stuff you can make using only the browser and some familiar JavaScript code.
Handle Mouse And Touch Input With The Pointer Events API
In this quick tutorial we present you the Pointer Events interface - a new JavaScript API that improves the way we handle touch and stylus input on the web.Handle Mouse And Touch Input With The Pointer Events API
With more and more people using their mobile phones and tablets for web browsing, we as developers have to make sure that our web interfaces are fully accessible via touch. Setting up click
and hover
event listeners sort of works, but it is clearly a leftover solution from the mouse era.
Thankfully, there is a new API in town that accommodates the needs of mouse, touch, and stylus devices. It’s called Pointer events (not to be mistaken with the CSS property of the same name) and it allows us to add event listeners that are better suited for working with all types on input.
Meet The New Events
The new Pointer Event API is an evolved version of the Mouse Event interface we’ve all been using so far. It extends the functionality of the old API and adds support for multi-touch gestures, precise pen input, and overall smoother touchscreen interaction.
- pointerdown – Pointer becomes active
- pointerup – Pointer stops being active
- pointerover, pointerenter – Pointer enters element boundries
- pointerout, pointerleave – Pointer leaves element boundries
- pointermove – Pointer moves while inside the element’s boundries
- pointercancel – Pointer has stopped generating events, e.g. input device deactivated
- gotpointercapture – Pointer has entered pointer capture state, e.g. dragging a movable element
- lostpointercapture – Pointer capture state has ended
Most of the Pointer Events have direct alternatives among the old mouse events. Once the new API gets full browser support we can directly substitute with the more modern alternatives:
const button = document.querySelector("button"); // Instead of mouseover button.addEventListener('mouseover', doSomething); // We can use pointerover button.addEventListener('pointerover', doSomething);
Interacting with a mouse should be the same in both cases. Using fingers or a stylus, however, will be easier to program with the new API.
Recognizing Input Type
An awesome feature of the Pointer Events API is that it can tell which type of input has been used. This can be helpful when you want to ignore some of the input methods or provide special feedback for each one.
button.addEventListener('pointereover', function(ev){ switch(ev.pointerType) { case 'mouse': // The used device is a mouse or trackpad. break; case 'touch': // Input via touchscreen. break; case 'pen': // Stylus input. break; default: // Browser can't recognize the used device. break; } });
Other Properties
The Pointer Events interface provides some some other interesting data as well. It includes all the MouseEvent properties plus the following:
- pointerId – Unique ID for the pointer causing the event.
- width and height – Size of the contact area in pixels.
- pressure – Pressure of touch, if available.
- tiltX and tiltY – The angle at which a stylus is touching the screen.
- isPrimary – Determines whether an event has been emitted by the pirmary pointer device.
Browser Support
Pointer Events are fairly new, so browser compatibility isn’t perfect yet. Chrome (desktop and mobile), Edge, IE, and Opera have full support; Firefox and Safari don’t.
To check whether a browser has the Pointer Events API you can use the window object:
if (window.PointerEvent) { // Pointer Events enabled. } else { // Pointer Events not supported }
A popular open-source pollyfill is also available for those who don’t want to wait for full browser adoption.
Conclusion
Although it doesn’t have full browser support yet, the Pointer Events API is eventually going to take over the old mouse events. It provides a lot of cool features that will increase web accessibility and enable developers to create more advanced touch and stylus-based apps.
If you want to learn more about the Power Events API we recommend checking out these resources:
- Pointing the Way Forward – Article on Google Developers
- Pointer Events – Level 2 – W3C Editor’s Draft
- Pointer Events on MDN