The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM

The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM

The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM

Oliver Williams


For even the simplest of components, the cost in human-labour may have been significant. UX teams do usability testing. An array of stakeholders have to sign off on the design.

Developers conduct AB tests, accessibility audits, unit tests and cross-browser checks. Once you’ve solved a problem, you don’t want to repeat that effort. By building a reusable component library (rather than building everything from scratch), we can continuously utilize past efforts and avoid revisiting already solved design and development challenges.

A screenshot of Google’s material components website – showing various components.
Large preview

Building an arsenal of components is particularly useful for companies such as Google that own a considerable portfolio of websites all sharing a common brand. By codifying their UI into composable widgets, larger companies can both speed up development time and achieve consistency of both visual and user-interaction design across projects. There’s been a rise in interest in style guides and pattern libraries over the last several years. Given multiple developers and designers spread over multiple teams, large companies seek to attain consistency. We can do better than simple color swatches. What we need is easily distributable code.

Sharing And Reusing Code

Manually copy-and-pasting code is effortless. Keeping that code up-to-date, however, is a maintenance nightmare. Many developers, therefore, rely on a package manager to reuse code across projects. Despite its name, the Node Package Manager has become the unrivalled platform for front-end package management. There are currently over 700,000 packages in the NPM registry and billions of packages are downloaded every month. Any folder with a package.json file can be uploaded to NPM as a shareable package. While NPM is primarily associated with JavaScript, a package can include CSS and markup. NPM makes it easy to reuse and, importantly, update code. Rather than needing to amend code in myriad places, you change the code only in the package.

The Markup Problem

Sass and Javascript are easily portable with the use of import statements. Templating languages give HTML the same ability — templates can import other fragments of HTML in the form of partials. You can write the markup for your footer, for example, just once, then include it in other templates. To say there exists a multiplicity of templating languages would be an understatement. Tying yourself to just one severely limits the potential reusability of your code. The alternative is to copy-and-paste markup and to use NPM only for styles and javascript.

This is the approach taken by the Financial Times with their Origami component library. In her talk “Can’t You Just Make It More like Bootstrap?” Alice Bartlett concluded “there is no good way to let people include templates in their projects”. Speaking about his experience of maintaining a component library at Lonely Planet, Ian Feather reiterated the problems with this approach:

“Once they copy that code they are essentially cutting a version which needs to be maintained indefinitely. When they copied the markup for a working component it had an implicit link to a snapshot of the CSS at that point. If you then update the template or refactor the CSS, you need to update all versions of the template scattered around your site.”

A Solution: Web Components

Web components solve this problem by defining markup in JavaScript. The author of a component is free to alter markup, CSS, and Javascript. The consumer of the component can benefit from these upgrades without needing to trawl through a project altering code by hand. Syncing with the latest changes project-wide can be achieved with a terse npm update via terminal. Only the name of the component and its API need to stay consistent.

Installing a web component is as simple as typing npm install component-name into a terminal. The Javascript can be included with an import statement:

<script type="module">
import './node_modules/component-name/index.js';

Then you can use the component anywhere in your markup. Here is a simple example component that copies text to the clipboard.

See the Pen Simple web component demo by CSS GRID (@cssgrid) on CodePen.

A component-centric approach to front-end development has become ubiquitous, ushered in by Facebook’s React framework. Inevitably, given the pervasiveness of frameworks in modern front-end workflows, a number of companies have built component libraries using their framework of choice. Those components are reusable only within that particular framework.

A component from IBM’s Carbon Design System
A component from IBM’s Carbon Design System. For use in React applications only. Other significant examples of component libraries built in React include Atlaskit from Atlassian and Polaris from Shopify. (Large preview)

It’s rare for a sizeable company to have a uniform front-end and replatorming from one framework to another isn’t uncommon. Frameworks come and go. To enable the maximum amount of potential reuse across projects, we need components that are framework agnostic.

A screenshot from showing components that do that same thing built exclusively for particular javascript frameworks.
Searching for components via reveals a fragmented Javascript ecosystem. (Large preview)

A graph charting the popularity of frameworks over time. Ember, Knockout and Backbone have plunged in popularity, replaced by newer offerings.
The ever-changing popularity of frameworks over time. (Large preview)

“I have built web applications using: Dojo, Mootools, Prototype, jQuery, Backbone, Thorax, and React over the years…I would love to have been able to bring that killer Dojo component that I slaved over with me to my React app of today.”

Dion Almaer, Director of Engineering, Google

When we talk about a web component, we are talking about the combination of a custom element with shadow DOM. Custom Elements and shadow DOM are part of both the W3C DOM specification and the WHATWG DOM Standard — meaning web components are a web standard. Custom elements and shadow DOM are finally set to achieve cross-browser support this year. By using a standard part of the native web platform, we ensure that our components can survive the fast-moving cycle of front-end restructuring and architectural rethinks. Web components can be used with any templating language and any front-end framework — they’re truly cross-compatible and interoperable. They can be used everywhere from a WordPress blog to a single page application.

The Custom Elements Everywhere project by Rob Dodson documents the interoperability of web components with various client-side Javascript frameworks.
The Custom Elements Everywhere project by Rob Dodson documents the interoperability of web components with various client-side Javascript frameworks. React, the outlier here, will hopefully resolve these issues with React 17. (Large preview)

Making A Web Component

Defining A Custom Element

It’s always been possible to make up tag-names and have their content appear on the page.

<made-up-tag>Hello World!</made-up-tag>

HTML is designed to be fault tolerant. The above will render, even though it’s not a valid HTML element. There’s never been a good reason to do this — deviating from standardized tags has traditionally been a bad practice. By defining a new tag using the custom element API, however, we can augment HTML with reusable elements that have built-in functionality. Creating a custom element is much like creating a component in React — but here were extending HTMLElement.

class ExpandableBox extends HTMLElement {
      constructor() {

A parameter-less call to super() must be the first statement in the constructor. The constructor should be used to set up initial state and default values and to set up any event listeners. A new custom element needs to be defined with a name for its HTML tag and the elements corresponding class:

customElements.define('expandable-box', ExpandableBox)

It’s a convention to capitalize class names. The syntax of the HTML tag is, however, more than a convention. What if browsers wanted to implement a new HTML element and they wanted to call it expandable-box? To prevent naming collisions, no new standardized HTML tags will include a dash. By contrast, the names of custom elements have to include a dash.

customElements.define('whatever', Whatever) // invalid
customElements.define('what-ever', Whatever) // valid

Custom Element Lifecycle

The API offers four custom element reactions — functions that can be defined within the class that will automatically be called in response to certain events in the lifecycle of a custom element.

connectedCallback is run when the custom element is added to the DOM.

connectedCallback() {
    console.log("custom element is on the page!")

This includes adding an element with Javascript:

document.body.appendChild(document.createElement("expandable-box")) //“custom element is on the page”

as well as simply including the element within the page with a HTML tag:

<expandable-box></expandable-box> // "custom element is on the page"

Any work that involves fetching resources or rendering should be in here.

disconnectedCallback is run when the custom element is removed from the DOM.

disconnectedCallback() {
    console.log("element has been removed")
document.querySelector("expandable-box").remove() //"element has been removed"

adoptedCallback is run when the custom element is adopted into a new document. You probably don’t need to worry about this one too often.

attributeChangedCallback is run when an attribute is added, changed, or removed. It can be used to listen for changes to both standardized native attributes like disabled or src, as well as any custom ones we make up. This is one of the most powerful aspects of custom elements as it enables the creation of a user-friendly API.

Custom Element Attributes

There are a great many HTML attributes. So that the browser doesn’t waste time calling our attributeChangedCallback when any attribute is changed, we need to provide a list of the attribute changes we want to listen for. For this example, we’re only interested in one.

static get observedAttributes() {
            return ['expanded']

So now our attributeChangedCallback will only be called when we change the value of the expanded attribute on the custom element, as it’s the only attribute we’ve listed.

HTML attributes can have corresponding values (think href, src, alt, value etc) while others are either true or false (e.g. disabled, selected, required). For an attribute with a corresponding value, we would include the following within the custom element’s class definition.

get yourCustomAttributeName() {
  return this.getAttribute('yourCustomAttributeName');
set yourCustomAttributeName(newValue) {
  this.setAttribute('yourCustomAttributeName', newValue);

For our example element, the attribute will either be true or false, so defining the getter and setter is a little different.

get expanded() {
  return this.hasAttribute('expanded')
// the second argument for setAttribute is mandatory, so we’ll use an empty string
set expanded(val) {
  if (val) {
    this.setAttribute('expanded', '');
  else {

Now that the boilerplate has been dealt with, we can make use of attributeChangedCallback.

attributeChangedCallback(name, oldval, newval) {
  console.log(`the ${name} attribute has changed from ${oldval} to ${newval}!!`);
  // do something every time the attribute changes

Traditionally, configuring a Javascript component would have involved passing arguments to an init function. By utilising the attributeChangedCallback, its possible to make a custom element that’s configurable just with markup.

Shadow DOM and custom elements can be used separately, and you may find custom elements useful all by themselves. Unlike shadow DOM, they can be polyfilled. However, the two specs work well in conjunction.

Attaching Markup And Styles With Shadow DOM

So far, we’ve handled the behavior of a custom element. In regard to markup and styles, however, our custom element is equivalent to an empty unstyled <span>. To encapsulate HTML and CSS as part of the component, we need to attach a shadow DOM. It’s best to do this within the constructor function.

class FancyComponent extends HTMLElement {
        constructor() {
            var shadowRoot = this.attachShadow({mode: 'open'})
            shadowRoot.innerHTML = `<h2>hello world!</h2>`

Don’t worry about understanding what the mode means — its boilerplate you have to include, but you’ll pretty much always want open. This simple example component will just render the text “hello world”. Like most other HTML elements, a custom element can have children — but not by default. So far the above custom element we’ve defined won’t render any children to the screen. To display any content between the tags, we need to make use of a slot element.

shadowRoot.innerHTML = `
<h2>hello world!</h2>

We can use a style tag to apply some CSS to the component.

shadowRoot.innerHTML = 
p {
color: red;
<h2>hello world!</h2>
<slot>some default content</slot>`

These styles will only apply to the component, so we are free to make use of element selectors without the styles affecting anything else of the page. This simplifies writing CSS, making naming conventions like BEM unnecessary.

Publishing A Component On NPM

NPM packages are published via the command line. Open a terminal window and move into a directory that you would like to turn into a reusable package. Then type the following commands into the terminal:

  1. If your project doesn’t already have a package.json, npm init will walk you through generating one.
  2. npm adduser links your machine to your NPM account. If you don’t have a preexisting account, it will create a new one for you.
  3. npm publish

NPM packages are published via the command line
Large preview

If all’s gone well, you now have a component in the NPM registry, ready to be installed and used in your own projects — and shared with the world.

An example of a component in the NPM registry, ready to be installed and used in your own projects.
Large preview

The web components API isn’t perfect. Custom elements are currently unable to include data in form submissions. The progressive enhancement story isn’t great. Dealing with accessibility isn’t as easy as it should be.

Although originally announced in 2011, browser support still isn’t universal. Firefox support is due later this year. Nevertheless, some high-profile websites (like Youtube) are already making use of them. Despite their current shortcomings, for universally shareable components they’re the singular option and in the future we can expect exciting additions to what they have to offer.

Smashing Editorial
(il, ra, yk)

Source link

How to Apply CSS3 Transforms to Background Images

CSS transformations are really cool, but they don’t yet apply to background images. This article presents a neat workaround for those times when you really do want to rotate a background image, or to keep a background image fixed while its container element is rotate.

This article was updated in 2018.

Interested in mastering CSS3 like a pro? CSS Master, by Tiffany Brown, is available for download to all SitePoint Premium members. Alternatively, you can grab your copy of the book for just $19.

Scaling, skewing and rotating any element is possible with the CSS3 transform property. It’s supported in all modern browsers without vendor prefixes. (I’ve added in the -webkit- just in case you want to support some older browsers.)

[code language=”css”]
#myelement {
-webkit-transform: rotate(30deg);
transform: rotate(30deg);

Great stuff. However, this rotates the whole element — its content, border and background image. What if you only want to rotate the background image? Or what if you want the background to remain fixed while the element is rotated?

Currently, there’s no W3C proposal for background-image transformations. It would be incredibly useful, so I suspect one will appear eventually, but that doesn’t help developers who want to use similar effects today.

Fortunately, there is a solution. In essence, it’s a hack which applies the background image to a before or after pseudo element rather than the parent container. The pseudo element can then be transformed independently.

The post How to Apply CSS3 Transforms to Background Images appeared first on SitePoint.

Source link

Bing Maps Routing API Adds Waypoint Optimization

Microsoft has added waypoint optimization to the Bing Maps Routing API, which allows developers to create routes between driving locations. 

Source link

abc to SVG

Here’s a little example that Jeremy Keith used to use in his talks. It’s stuck with me as one of the coolest examples of progressive enhancement and Technology Being CoolTM around.

There is this musical notation format called abc. They don’t capitalize it. Kinda like npm, which I guess makes sense as it isn’t an acronym. But it is the name of something so it’s super awkward. Ughakdhk. Anyway.

The format itself is really cool. It’s super simple and text-based. Here’s the example from their homepage:

T:Speed the Plough
|:GABc dedB|dedB dedB|c2ec B2dB|c2A2 A2BA|
  GABc dedB|dedB dedB|c2ec B2dB|A2F2 G4:|
|:g2gf gdBd|g2f2 e2d2|c2ec B2dB|c2A2 A2df|
  g2gf g2Bd|g2f2 e2d2|c2ec B2dB|A2F2 G4:|

A little like YAML, I suppose. That’s the music for that whole song. It’s not loaded with all the possibilities of sheet music; it’s just notes and timing. Enough to communicate a folk/traditional song, which is primarily what it’s used for.

You could probably get used to reading it as-is, but I don’t think that’s what it’s really for. My guess is that the format is more about being:

  1. Standardized (it is, and there are 570,000 tunes in it, so I guess that worked)
  2. Text (I bet that entire database of songs is surprisingly tiny)
  3. Ready to be converted into whatever

The conversion part being the fun part! You can see it happening right on the homepage for the abc format.

Lonesome Moonlight Waltz, stored in abc format on the site, is being displayed as sheet music in PNG format and being converted into a an audio format playable on the web. Basically MIDI barfed out as MP3.

PNG is fine, but wouldn’t that be so much nicer as SVG? Of course it would.

All of this is relevant to Jeremy because he has a website called The Session, which is dedicated to Irish music. He stores tunes on the site, and thus appropriately uses the abc format. On The Session, you can click a Sheet Music button and it will convert abc into SVG and display that.

That sheet music looks great in the crisp SVG format.

The SVG conversion is made possible entirely in JavaScript by an open source library. That’s the progressive enhancement part. Store and ship the basic format, and let the browser enhance the experience, if it can (it can).

That’s all. Just cool.

The post abc to SVG appeared first on CSS-Tricks.

Source link

So You Want to Persuade Users? Make Things Simple!

So You Want to Persuade Users? Make Things Simple!

So You Want to Persuade Users? Make Things Simple!

Lyndon Cerejo


(This article is kindly sponsored by Adobe.) The persuasive design toolbox is filled with powerful tools based on psychology. These tools range from Cialdini’s set of six principles of persuasion to ten times that number of Persuasive Patterns. Presented with all these methods, it can be tempting to use all of them to cover all possible bases, using a shotgun approach, hoping that one will resonate with your target users.

However, applying persuasion principles and patterns in a haphazard manner just ends up being persuasive design clutter. Like user experience design, designing for everyone is designing for no one. Randomly thrown together persuasive techniques will also make users feel manipulated, not in control, making them abandon the site or experience. The key to persuading your users is to keep it simple: using focused persuasive techniques and tactics that will work for your users.

Persuasion Funnel

AIDA is an acronym used in marketing and advertising to describe the stages that a customer goes through in the purchase process. The stages of Attention, Interest, Desire and Action, generically follow a series of cognitive (thinking) and affective (feeling) stages culminating in a behavioral (doing e.g. purchase or trial) stage. This should sound familiar since this is what we do through design, especially persuasive design.

When it comes to persuasive design, users go through a few stages between Awareness and Action, and the design should guide them from one stage to the next. I don’t have a clever acronym for it (yet), but the stages the design has to take the users through are:

  • Awareness
  • Relevant
  • Credible
  • Usable
  • Desirable
  • Persuasive
  • Action

(Large preview)

When users are contemplating an action (like booking a hotel room), they have to be aware of your site, app, or experience. Once they begin their journey on your site, they quickly evaluate the experience and either proceed to the next step or leave and go elsewhere. With fewer users continuing to subsequent stages, the number of users at each stage begins to resemble the shape of a funnel as shown above.

Let’s peek inside what could be going on in hypothetical users’ minds as they go through the experience of booking a hotel room for New Year’s Eve in Times Square, and some of the reasons they may drop off in each stage.


“Hmmm… Where do I start? Hotel chains promise the lowest rate if we book directly with them, but I won’t be able to see other hotel options around Times Square. Hotel… Maybe I should try an online travel agency like Trivago (looks like the Trivago guy / Trivago girl advertising works!) to find a wider range of hotels. I’m going to also quickly Google it to see if there are other options.”

Users have to be aware of your site, app or experience to use it — Duh!


“I found HotelTonight on Google. It looks like a great way to get rooms last minute, but not this far in advance — it’s not relevant to me.”

If your experience is not relevant to the task they are trying to accomplish, users will leave and try elsewhere. If your products or services are relevant, but not findable by the user, work on your navigation, search, and content layout to ensure your products and services are visible. Everything does not have to be one click away, but if the user gets the scent of information, or cues that make them think they are on the right path, they will follow the trail to that information.


“This design looks like it hasn’t been updated since the [GeoCities era](

— Warning bells go off in head —

I’m out of here.”

Users are aware of many of the risks available online and look for trust indicators including a known brand and domain, secure site, professional design, real-world contact information and third-party certificates or badges. Incorporate these elements to create a comfort level for the user.


“I can’t figure out where things are in the navigation, and the search results had hundreds of unhelpful results. The homepage has nice big images, but that meant I had to scroll before I could see any real content.”

Usability is surprisingly still an issue with many sites. Follow User Experience best practices during design, and test with users to validate that the design is usable.


“This reminds me of Craigslist — it is usable, but the design does not make me want to stay and use it. I’ll try that other hotel website that provides an immersive, interactive experience as I search for hotels.”

As much as we like to believe it, users’ decisions are not always rational, and very often driven by emotion, and we can address that through design. Usability is about making it work well; this is about making it beautiful as well.

In his book Emotional Design, Don Norman explains: “Attractive things do work better — their attractiveness produces positive emotions, causing mental processes to be more creative, more tolerant of minor difficulties.” Don talks about the three different aspects of design: visceral, behavioral, and reflective. Visceral design is about appearance, behavioral about the pleasure and effectiveness of use, and reflective design involves the rationalization and intellectualization of a product.


“Oh, Wow! That’s a long list of hotels, with plenty of availability for New Year’s Eve. There’s no real reason to book now. I’ll just come back to book after Thanksgiving…”

The user was interested, able, and willing, but the design did not motivate him to take intended action. Use relevant persuasion techniques that apply to your user to move them toward the desired action.

Examples of persuasive methods while shopping on Travelocity for a hotel room for New Year’s Eve.
Examples of persuasive methods while shopping on Travelocity for a hotel room for New Year’s Eve. (Large preview)


“Oh, Wow! 65% of hotels are already booked in this area for New Year’s Eve. I better make a reservation now. . This looks like a nice hotel, and it also offers free cancellation – I’m reserving it now!”

The user who made it to this stage was interested, able, and willing, and the design nudged him to take intended action of making a reservation before leaving the site.

Persuasion is not about applying all available principles and patterns to your designs, but systematically identifying how you can address users’ barriers and motivators during each step of the journey, and guiding your users through the funnel to take the desired action.

The KISS Approach

Most of us are familiar with the acronym KISS: “Keep It Simple, Stupid,” a principle advocating simplicity as a key goal in design by avoiding unnecessary complexity. Let’s borrow that acronym for a 4-step approach to persuasive design.

Know The Right Behavior To Target

The first step is knowing the behavior you would like to target, and identifying the simplest action that can lead to that behavior change. Take the example of term life insurance companies who, to put it very bluntly, stand to benefit if their policyholders are healthy and don’t die while the policy is active. While those companies have a long-term ambitious goal of helping their policyholders lead healthy lives (mutually beneficial), that could be broken down into a simpler target behavior of walking 10,000 steps daily. This behavior is simple to understand, achieve, measure, and contributes to the long-term goal of healthier policyholders.

One such insurance company is offering new policyholders the latest Apple Watch for a low initial down payment ($25). The ongoing monthly payments can be waived each month that the policyholder leads an active lifestyle and exercises regularly (e.g. walks about 10,000 steps a day). About half the people who participated have achieved monthly goals, despite potential privacy implications.

John Hancock Term Life Insurance Apple Watch offer targets walking about 10,000 steps a day.
John Hancock Term Life Insurance Apple Watch offer targets walking about 10,000 steps a day. (Large preview)

Identify Barriers And Motivators

User research for persuasive design digs below the surface thinking level to the feeling level, and moves beyond the rational to the emotional level, as shown below. Getting to know your users at a deeper level will help you use psychology to focus your design to get users to engage in the target behavior identified above. User interviews that focus on users’ feelings and emotions are used to uncover barriers and motivators they consciously or subconsciously face while trying to achieve the target behavior. This helps us identify which blocks we need to weaken, and which motivators we should strengthen, through persuasive design techniques and tactics.

Tip of the iceberg user research diagram
(Large preview)

Simplify The Experience

Simplify the design experience of the first stages of the funnel, as users go through the mental verifications of relevancy, credibility, and usability of the experience. This includes making it easy for the user to find what they are looking for, credibility indicators like professional design, contact information, and third-party certificates or badges, as well as addressing usability issues. As Steve Krug put it very succinctly: “Don’t Make Me Think”.

Select Appropriate Triggers

Users who have made it this far in the process are interested in something you have to offer. As a designer, you have to nudge them to take the desired action. A good starting point is Robert Cialdini’s, six key principles of persuasion:

  1. Reciprocity
    People are obliged to give something back in exchange for receiving something.
  2. Scarcity
    People want more of those things they can have less of.
  3. Authority
    People follow the lead of credible, knowledgeable experts.
  4. Consistency
    People like to be consistent with the things they have previously said or done.
  5. Liking
    People prefer to say yes to those that they like.
  6. Consensus (Social Proof)
    Especially when they are uncertain, people will look to the actions and behaviors of others to determine their own.

These principles can be applied through dozens of different persuasive design patterns and methods, some of which have been previously published on Smashing Magazine (patterns, triggers), or in the books listed in the resources at the end. As you may notice, many persuasive patterns are related to UI patterns, because part of persuasion is reducing friction and simplifying what the user needs to do at any given point in time. For example, the persuasive pattern of Limited Choice can be realized through UI Pattern of Progressive Disclosure.

Given that there are dozens of patterns and methods (depending on where you look), it is important to selectively use methods that will resonate with your users. Applying all design patterns in the hope of some working will result in persuasion clutter and overwhelm the user, possibly driving them away from your site.

Examining Persuasion

Let’s take a closer look at the earlier example of the term life insurance through the eyes of someone who is motivated (shopping for life insurance) and has the ability (to pay monthly life insurance cost). Like me, let’s assume that this user was made aware of this through a sponsored post on Facebook. During the stages of awareness and relevance, there are a few persuasive triggers as shown below that make the user click “Learn More”.

(Large preview)

Clicking the “Learn More” button takes the user to a landing page that we will examine in sections for a persuasive flow:

(Large preview)

The user’s primary motivation in shopping for term life insurance is: “Protect Family,” and a big barrier is “High Cost.”

  1. Reputable Name (Credibility)
    Even if you’ve not heard of this company, John Hancock is a famous person and the term used as a synonym in the United States for one’s signature. The company reinforces it’s longevity later on the page.
  2. Toll-free Number (Credibility)
    Established and legitimate organization.
  3. Message Framing
    Live healthy, is also reinforced by the image of a family enjoying outdoors.

    “This life insurance product will help me live longer, lead a happy life like them, and protect my family in case something happens, and won’t cost much.”

  4. People Like Me & Association
    This family looks like mine (or the family next door) — I can see myself in this wide-open field (visceral and reflective triggers).
  5. Extrinsic Reward
    An Apple watch for $25 — that’s a bonus here!
  6. Visual Cueing
    The person in focus (stereotypical breadwinner) has his gaze directly focused at the form below, leading the user to the next step.
  7. Foot In The Door
    This quote won’t cost anything — zip, nada.
  8. Computer As A Social Actor
    The information takes a conversational tone and format, not the usual form in rows and columns. The information seems reasonable to generate a quote.
  9. Commitment & Consistency
    By filling this quick, easy, and free form, chances are that the user will act consistently and proceed when it comes to the next step (application), unless there’s another barrier (price, benefits, etc.)

    (Large preview)
  10. Control
    The user has a choice of devices.
  11. Extrinsic Rewards
    More rewards to be earned.
  12. Control
    The user controls how much they pay (the more active, the less you’ll pay). Also, in case the user does is not active, the cost is framed as just $13 (for a month).
  13. Credibility
    The company reinforces longevity and protector of America.
  14. Authority
    Licensed Coverage Coach (not just a sales agent).
  15. Flow
    One way to keep users in the flow and not get distracted is by disabling the social media links (which could raise the question: why display them?).

That took longer to dissect and read than it does in real life, where most of this is processed consciously and subconsciously in a few seconds, often with a glance or two.

Apart from the methods establishing credibility, the persuasive methods are used to strengthen the primary motivator of “Protect Family” (get insurance, extrinsic reward will help me live longer for my family), and weaken the barrier of “High Cost” (low monthly cost, additional savings, no ongoing watch payments). Note how they work together and don’t conflict or clutter the experience.


Persuasion is all around us, in our everyday lives. As designers, we can use ethical persuasive design methods to get users to take some action. With plenty of persuasive methods available, we have to be selective about what we use. We can use the KISS approach to keep it simple:

  • Know the right behavior to target
  • Identify barriers and motivators
  • Simplify the experience
  • Select appropriate triggers

KISS also reminds us to Keep It Simple & Straightforward, by selecting a simple target behavior, simplifying the experience for the user, and by applying persuasive techniques that will lead to the target behavior without overwhelming the user.

Further Reading

This article is part of the UX design series sponsored by Adobe. Adobe XD tool is made for a fast and fluid UX design process, as it lets you go from idea to prototype faster. Design, prototype, and share — all in one app. You can check out more inspiring projects created with Adobe XD on Behance, and also sign up for the Adobe experience design newsletter to stay updated and informed on the latest trends and insights for UX/UI design.

Smashing Editorial
(yk, il)

Source link

5 Great HTML5 Video Players

There has been an increasing demand for creators to develop their own custom video platform which they can use to advance their own advertising, marketing or branding goals. Although YouTube and other similar platforms are generally more promising, hosting videos on your own and using a video player of your choice offers more control over how your videos are used.

Irrespective of whether you are a YouTube video creator or social media influencer, we've compiled a list of 5 of the greatest HTML5 video players. This list has been compiled after taking into consideration a few important needs, such as:

  1. Fast and responsive
  2. Easy to install and use
  3. Compatibility quotient across browsers
  4. Robust and all round playlist options
  5. Ability to include an advertisement at various stages of the video – before, during or after
  6. Ability to integrate self-hosted videos with those from channels like YouTube, Dailymotion, Vimeo, etc.

Now that we have an idea what to look for, here is a list of the top 5 HTML5 Video Players.


VideoJS, an open source HTML5 video player is built using JavaScript and CSS. It's an HTML5 video player with optional support for Flash. Having Flash as a fallback option is especially helpful when you're using it on browsers that do not support HTML5. It can extend its support to Vimeo and YouTube.

Launched in the year 2010, VideoJS currently serves more than 400,000 websites across the internet. VideoJS is equally compatible on mobile devices as well as desktops.

Some of the top features of VideoJS include:

  1. Plugin Support: VideoJS supports multiple plugins like analytics, advertising, playlists as well as support for advanced formats such as HLS and DASH. A full list of supported plugins can be found VideoJS plugin page.
  2. Skinning: Everything about VideoJS is customizable. You can easily customize the way it looks by editing the CSS style. Steve Heffernan has a codepen demo for customizing VideoJS skin that should help you get started.
  3. Ready adaptability to various plugins makes this player much more useful. Some sample plugins include:
    1. Analytics: Ability to track Google Analytics events from the VideoJS player
    2. Brand: You can add the logo of your brand to the player
    3. Playlist: Support for playlists
    4. Chromecast: Ability to cast a video to a device using a Chromecast device

JW Player

JW Player has been around for ages and was one of the most popular Flash video players for the web. Later on, it extended its support for HTML5 video playback. JW Player is completely customizable, has a responsive HTML5 video and has a large variety of features right from analytics support to accessibility and full HTML5 video controls.

It has perhaps the best website video player with its wide array of video supported solutions. JW player also works very well as an HTML5 video player for WordPress websites. It can also be used as an alternate option for YouTube's video player. Interestingly, before Google purchased YouTube, the original YouTube video player was based on JW Player.

One of the key reasons that the JW Player is above its peers in this category because of the sheer amount of features it provides via a number of different add-ons. These can range from advertising partnerships to closed captions as well as popular social networking tools.

As mentioned earlier, the player is completely customizable and supports a number of custom user-defined themes. It also comes with an integrated API. It has a number of different plugins to support the more popular CMSs, which makes integration fairly simple.

Kaltura HTML5 Video Player

Kaltura Player is a free-to-use, open source HTML5 video player that can be used to create multiple and custom inter-browser and inter-device skins that can match or complement the design of your website. The Kaltura player comes with numerous player templates to choose from.

Some of the key features include:

  1. Robust, all-round Performance
  2. Multi-platform support
  3. Advertising & Analytics: It supports most ad formats including VAST v. 3.0 as well as integrated plugins that can be used across a wide range of video ad networks. These include Google's Doubleclick Ad Platform, FreeWheel, Eye Wonder, Ad Tech, Tremor Video, AdapTV and many more.


Flowplayer is an extremely simple video player for creators who wish to include video playback on their websites. Integrating and the markup process for Flowplayer is decidedly straightforward, which is one of its major benefits.

At the outset, it is important to note that Flowplayer is primarily aimed at those creators who host video files independently. In case creators are using a streaming service such as Vimeo or YouTube, both streaming services provide code that can be used to embed the player itself onto the website or landing page.

Flowplayer is 100% customizable as well as skinnable and comes with support for including subtitles, modifying the playback speed, including video analytics and monetization opportunities.

The post 5 Great HTML5 Video Players appeared first on SitePoint.

Source link

The ID Co Launches Open Banking API Platform

The ID Co. is excited to announce the launch and immediate availability of the Open Banking API Platform with full support for all of the leading UK banks.

Source link

On xlink:href being deprecated in SVG

A reader wrote in to tell me we should update our articles about SVG <use> elements. The attribute we always use for them, xlink:href, is deprecated. Indeed, MDN says:

Deprecated since SVG 2
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

That’s pretty strong language, hence the reader’s warning. This is a bit surprising to me, as the SVG 2 thing got a little weird. It looks like it did become a Candidate Recommendation though.


<!-- This is old -->
  <use xlink:href="#whatever" />

<!-- This is new -->
  <use href="#whatever" />

I like it. But does it actually work? Lemme fork my little old demo and change all the references. In a quick run through of what I have easy access to:

Chrome 67 Firefox 61 Safari 11 Edge 17 IE 11 iOS 11
🙅‍♂️ 🙅‍♂️

Better than I thought! But enough 🙅‍♂️ no-go’s there that up and switching everything seems far too dangerous, especially when xlink:href has support across the board.

Will browsers actually pull support? I’ll bet ya fifty bucks none of them ever do. There are tons of websites that use the attribute in the old format that will never update, and we know that browsers take breaking old sites very seriously (yay).

It feels like the same thing with, for example, :before and ::before. Yeah, ::before is the new and more correct syntax. But no browser will ever pull support for :before (I’ll bet ya another 50 bucks) because it just needlessly breaks sites. And because of that, it almost makes the most sense to keep using :before as you get the widest swath of support that way.

I probably won’t be updating older articles using <use xlink:href="" /> unless something bizarre happens and some browser actually does pull support.

The post On xlink:href being deprecated in SVG appeared first on CSS-Tricks.

Source link

3 Essential Design Trends, August 2018

From light and bright designs to complex data visualizations and a new take on polygons, this month’s design trends are anything but ordinary. And they are so practical you can deploy them on single pages or for a complete design overhaul.

Each of these trends shows and evolution of styles that’s been progressing for some time: minimalism to white and light color schemes, data “everything” to data visualization for the web, and a fresh look at poly shapes.

Here’s what’s trending in design this month:

1. White and Light Color Schemes

White and light color schemes seem to be popping up everywhere. (We could probably have dedicated an entire post to this design trend because there are so many designs featuring this color trend.)

The main characteristic of this design trend is an aesthetic that uses a predominant white or light color scheme. This includes the background, images and even other foreground elements. While white is a popular option, color palettes featuring soft grays, cool cream tones, and even some hardly noticeable pastels are equally impressive.

The trick to using this design technique is incorporating other elements so that you don’t just end up with a “plain” white background. Including imagery that also is light or features a lot of white can bring the design together pretty seamlessly, such as the example from Verho.

But there’s no rule that images are the only way to implement this design trend. Working with video (such as Omega Yeast) or an illustration (Alexandra Elisa) can be equally engaging.

Use this design trend for a full website theme or opt for a section or page with a light to white design to add particular emphasis to that area. Just make sure to go with a dark text option so that lettering is easy to read.

Add an extra layer of emphasis with a bright colored button or single element so that users find the most important part of the design right away. Consider accent colors in the style of minimalism rather than full color options; a simple one-color concept can work amazingly well.

2. Data Visualization

Data, data everywhere.

Or that seems to be the case anyway.

With such an emphasis on data and information gathering and delivery across industries to provide valuable and reliable information, it’s no real surprise that more designs are featuring large-scale data visualizations.

From maps to charts to interactive animations, a solid data visualization can help a user better understand a topic or information and provide an engaging (and memorable) way to learn about something.

The downside is that it can be a rather large undertaking to manage all that data. Look for a method that allows you to showcase information in an up-to-date manner without the stress of constant management. Automated tools can help. (Google Charts is simple and pretty powerful.)

There are so many different ways to create, embed and include data visualizations in a website design. The most engaging websites using this trend have dynamic information presented in the most interactive formats.

Tree Tree Tree starts by asking the user to enter the location they are interested in learning more about. The result shows the wind speed using a tree with boxes that “blow” as speed increases. Users can also engage using the map at the bottom of the screen. This is data that is begging to be interacted with.

Tomorrow’s World starts with a survey that the user completes and ends with a cool visualization of how those answers compare to others. The data visualization is a tool to help the user learn about him/herself and the world around them. 

Qravity has multiple points of data entry in its website design. One of the most interesting might be the animated timeline below the scroll. This method of organizing information (dates and events) in a visual way makes the information so much easier to understand than a simple list.

3. Polygons 2.0

Polygon shapes in website design were everywhere in late 2017 and earlier this year. That trend continues but with a different look. Rather than piles of packed polygons to create backgrounds or other design elements, designers are picking a handful of polygons and supersizing them.

These oversized shapes add a fun and funky design element that matches almost any style of project. They can be part of an overall design pattern, accent on a homepage or interesting shape container element for an image or text.

What’s great about poly shapes is that they are a little different than the standard rectangles of circles that are more common and can immediate attract the attention of a user for that reason. These shapes also have a more modern feel because they are different.

Polygons can feature shapes that have more distinct angles and sides such as the sharp animated triangle to the right side of The Alan Turing Institute website, simple lines that overlap for a more traditional poly feel (Evoluted) or simple shapes that help raw users into specific content (Iqor).

Because poly shapes are such a distinct design element, most projects feature them with bright color for even more emphasis. Just be wary of trying to fit elements inside of tilted or odd shape configurations; this can make elements to text difficult to read.

Polygons are best suited as a background or accent element, not necessarily as a home for messaging or key content items.


Personally, I love the white and bright design trend. With the heat of summer in full swing, these designs are appealing in so many ways. I like how versatile they are as well. A light color scheme is so readable with dark text and can work for almost any type of design project.

What trends are you loving (or hating) right now? I’d love to see some of the websites that you are fascinated with. Drop me a link on Twitter; I’d love to hear from you.

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!


p img {display:inline-block; margin-right:10px;}
.alignleft {float:left;}
p.showcase {clear:both;}
body#browserfriendly p, body#podcast p, div#emailbody p{margin:0;}

Source link

What Do You Need To Know When Converting A Flash Game Into HTML5?

What Do You Need To Know When Converting A Flash Game Into HTML5?

What Do You Need To Know When Converting A Flash Game Into HTML5?

Tomasz Grajewski


With the rise of HTML5 usage, many companies start redoing their most popular titles to get rid of outdated Flash and match their products to the latest industry standards. This change is especially visible in the Gambling/Casino & Entertainment industries and has been happening for several years now, so a decent selection of titles has already been converted.

Unfortunately, when browsing the Internet, you can quite often stumble upon examples of a seemingly hasty job, which results in the lover quality of the final product. That’s why it’s a good idea for game developers to dedicate some of their time for getting familiar with the subject of Flash to HTML5 conversion and learning which mistakes to avoid before getting down to work.

Among the reasons for choosing JavaScript instead of Flash, apart from the obvious technical issues, is also the fact that changing your game design from SWF to JavaScript can yield a better user experience, which in turn give it a modern look. But how to do it? Do you need a dedicated JavaScript game converter to get rid of this outdated technology? Well, Flash to HTML5 conversion can be a piece of cake — here’s how to take care of it.

Recommended reading: Principles Of HTML5 Game Design

How To Improve HTML5 Game Experience

Converting a game to another platform is an excellent opportunity to improve it, fix its issues, and increase the audience. Below are few things that can be easily done and are worth considering:

  • Supporting mobile devices
    Converting from Flash to JavaScript allows reaching a broader audience (users of mobile devices); support for touchscreen controls usually needs to be implemented into the game, too. Luckily, both Android and iOS devices now also support WebGL, so 30 or 60 FPS rendering usually can be easily achieved. In many cases, 60 FPS won’t cause any problems, which will only improve with time, as mobile devices become more and more performant.

  • Improving performance
    When it comes to comparing ActionScript and JavaScript, the latter is faster than the first one. Other than that, converting a game is a good occasion to revisit algorithms used in game code. With JavaScript game development you can optimize them or completely strip unused code that’s left by original developers.
  • Fixing bugs and making improvements to the gameplay
    Having new developers looking into game’s source code can help to fix known bugs or discover new and very rare ones. This would make playing the game less irritating for the players, which would make them spend more time on your site and encourage to try your other games.
  • Adding web analytics
    In addition to tracking the traffic, web analytics can also be used to gather knowledge on how players behave in a game and where they get stuck during gameplay.
  • Adding localization
    This would increase the audience and is important for kids from other countries playing your game. Or maybe your game is not in English and you want to support that language?

Why Skipping HTML And CSS For In-Game UI Will Improve Game Performance

When it comes to JavaScript game development, it may be tempting to leverage HTML and CSS for in-game buttons, widgets, and other GUI elements. My advice is to be careful here. It’s counterintuitive, but actually leveraging DOM elements is less performant on complex games and this gains more significance on mobile. If you want to achieve constant 60 FPS on all platforms, then resigning from HTML and CSS may be required.

Non-interactive GUI elements, such as health bars, ammo bars, or score counters can be easily implemented in Phaser by using regular images (the Phaser.Image class), leveraging the .crop property for trimming and the Phaser.Text class for simple text labels.

Such interactive elements as buttons and checkboxes can be implemented by using the built-in Phaser.Button class. Other, more complex elements can be composed of different simple types, like groups, images, buttons and text labels.

Note: Each time you instantiate a Phaser.Text or PIXI.Text object, a new texture is created to render text onto. This additional texture breaks vertex batching, so be careful not to have too many of them.

How To Ensure That Custom Fonts Have Loaded

If you want to render text with a custom vector font (e.g. TTF or OTF), then you need to ensure that the font has already been loaded by the browser before rendering any text. Phaser v2 doesn’t provide a solution for this purpose, but another library can be used: Web Font Loader.

Assuming that you have a font file and include the Web Font Loader in your page, then below is a simple example of how to load a font:

Make a simple CSS file that will be loaded by Web Font Loader (you don’t need to include it in your HTML):

@font-face {
    // This name you will use in JS
    font-family: 'Gunplay';
    // URL to the font file, can be relative or absolute
    src: url('../fonts/gunplay.ttf') format('truetype');
    font-weight: 400;

Now define a global variable named WebFontConfig. Something as simple as this will usually suffice:

var WebFontConfig = {
   'classes': false,
   'timeout': 0,
   'active': function() {
       // The font has successfully loaded...
   'custom': {
       'families': ['Gunplay'],
       // URL to the previously mentioned CSS
       'urls': ['styles/fonts.css']

It the end, remember to put your code in the ‘active’ callback shown above. And that’s it!

How To Make It Easier For Users To Save The Game

To persistently store local data in ActionScript you would use the SharedObject class. In JavaScript, the simple replacement is localStorage API, which allows storing strings for later retrieval, surviving page reloads.

Saving data is very simple:

var progress = 15;
localStorage.setItem('myGame.progress', progress);

Note that in the above example the progress variable, which is a number, will be converted to a string.

Loading is simple too, but remember that retrieved values will be strings or null if they don’t exists.

var progress = parseInt(localStorage.getItem('myGame.progress')) || 0;

Here we’re ensuring that the return value is a number. If it doesn’t exist, then 0 will be assigned to the progress variable.

You can also store and retrieve more complex structures, for example, JSON:

var stats = {'goals': 13, 'wins': 7, 'losses': 3, 'draws': 1};
localStorage.setItem('myGame.stats', JSON.stringify(stats));
var stats = JSON.parse(localStorage.getItem('myGame.stats')) || {};

There are some cases when the localStorage object won’t be available. For example, when using the file:// protocol or when a page is loaded in a private window. You can use the try and catch statement to ensure your code will both continue working and use default values, what is shown in the example below:

try {
    var progress = localStorage.getItem('myGame.progress');
} catch (exception) {
    // localStorage not available, use default values

Another thing to remember is that the stored data is saved per domain, not per URL. So if there is a risk that many games are hosted on a single domain, then it’s better to use a prefix (namespace) when saving. In the example above 'myGame.' is such a prefix and you usually want to replace it with the name of the game.

Note: If your game is embedded in an iframe, then localStorage won’t persist on iOS. In this case, you would need to store data in the parent iframe instead.

How To Leverage Replacing Default Fragment Shader

When Phaser and PixiJS render your sprites, they use a simple internal fragment shader. It doesn’t have many features because it’s tailored for a speed. However, you can replace that shader for your purposes. For example, you can leverage it to inspect overdraw or support more features for rendering.

Below is an example of how to supply your own default fragment shader to Phaser v2:

function preload() {
    this.load.shader('filename.frag', 'shaders/filename.frag');

function create() {
    var renderer = this.renderer;
    var batch = renderer.spriteBatch;
    batch.defaultShader = 
        new PIXI.AbstractFilter(this.cache.getShader('filename.frag'));

Note: It’s important to remember that the default shader is used for ALL sprites as well as when rendering to a texture. Also, keep in mind that using complex shaders for all in-game sprites will greatly reduce rendering performance.

How To Change Tinting Method With A Default Shader

Custom default shader can be used to replace default tinting method in Phaser and PixiJS.

Tinting in Phaser and PixiJS works by multiplying texture pixels by a given color. Multiplication always darkens colors, which obviously is not a problem; it’s simply different from the Flash tinting. For one of our games, we needed to implement tinting similar to Flash and decided that a custom default shader could be used. Below is an example of such fragment shader:

// Specific tint variant, similar to the Flash tinting that adds
// to the color and does not multiply. A negative of a color
// must be supplied for this shader to work properly, i.e. set
// sprite.tint to 0 to turn whole sprite to white.
precision lowp float;

varying vec2 vTextureCoord;
varying vec4 vColor;

uniform sampler2D uSampler;

void main(void) {
    vec4 f = texture2D(uSampler, vTextureCoord);
    float a = clamp(vColor.a, 0.00001, 1.0);
    gl_FragColor.rgb = f.rgb * vColor.a + clamp(1.0 - vColor.rgb/a, 0.0, 1.0) * vColor.a * f.a;
    gl_FragColor.a = f.a * vColor.a;

This shader lightens pixels by adding a base color to the tint one. For this to work, you need to supply negative of the color you want. Therefore, in order to get white, you need to set:

sprite.tint = 0x000000;  // This colors the sprite to white
Sprite.tint = 0x00ffff;  // This gives red

The result in our game looks like this (notice how tanks flash white when hit):

Custom default shader (tanks flashing white).

How To Inspect Overdraw To Detect Fill Rate Issues

Replacing default shader can also be leveraged to help with debugging. Below I’ve explained how overdraw can be detected with such a shader.

Overdrawing happens when many or all pixels on the screen are rendered multiple times. For example, many objects taking the same place and being rendered one over another. How many pixels a GPU can render per second is described as fill rate. Modern desktop GPUs have excessive fill rate for usual 2D purposes, but mobile ones are a lot slower.

There is a simple method of finding out how many times each pixel on the screen is written by replacing the default global fragment shader in PixiJS and Phaser with this one:

void main(void) {
    gl_FragColor.rgb += 1.0 / 7.0;

This shader lightens pixels that are being processed. The number 7.0 indicates how many writes are needed to turn pixel white; you can tune this number to your liking. In other words, lighter pixels on screen were written several times, and white pixels were written at least 7 times.

This shader also helps to find both “invisible” objects that for some reason are still rendered and sprites that have excessive transparent areas around that need to be stripped (GPU still needs to process transparent pixels in your textures).

Example of the Overdraw shader in action in game development
Overdraw shader in action. (Large preview)

The picture on the left shows how a player sees the game, while the one on the right displays the effect of applying the overdraw shader to the same scene.

Why Physics Engines Are Your Friends

A physics engine is a middleware that’s responsible for simulating physics bodies (usually rigid body dynamics) and their collisions. Physics engines simulate 2D or 3D spaces, but not both. A typical physics engine will provide:

  • object movement by setting velocities, accelerations, joints, and motors;
  • detecting collisions between various shape types;
  • calculating collision responses, i.e. how two objects should react when they collide.

At Merixstudio, we’re big fans of the Box2D physics engine and used it on a few occasions. There is a Phaser plugin that works well for this purpose. Box2D is also used in the Unity game engine and GameMaker Studio 2.

While a physics engine will speed-up your development, there is a price you’ll have to pay: reduced runtime performance. Detecting collisions and calculating responses is a CPU-intensive task. You may be limited to several dozen dynamic objects in a scene on mobile phones or face degraded performance, as well as reduced frame rate deep below 60 FPS.

Example of the difference in the scene of a game with and withour Phaser physics debug overlay displayed on top
Phaser’s physics debug overlay. (Large preview)

The left part of the image is a scene from a game, while the right side shows the same scene with Phaser physics debug overlay displayed on top.

How To Export Sounds From A .fla File

If you have a Flash game sound effects inside of a .fla file, then exporting them from GUI is not possible (at least not in Adobe Animate CC 2017) due to the lack of menu option serving this purpose. But there is another solution — a dedicated script that does just that:

function normalizeFilename(name) {
   // Converts a camelCase name to snake_case name
   return name.replace(/([A-Z])/g, '_$1').replace(/^_/, '').toLowerCase();

function displayPath(path) {
   // Makes the file path more readable
   return unescape(path).replace('file:///', '').replace('|', ':');


if (fl.getDocumentDOM().library.getSelectedItems().length > 0)
   // Get only selected items
   var library = fl.getDocumentDOM().library.getSelectedItems();
   // Get all items
   var library = fl.getDocumentDOM().library.items;

// Ask user for the export destination directory
var root = fl.browseForFolderURL('Select a folder.');
var errors = 0;

for (var i = 0; i < library.length; i++) {
   var item = library[i];
   if (item.itemType !== 'sound')

   var path = root + '/';

   if (item.originalCompressionType === 'RAW')
       path += normalizeFilename('.')[0]) + '.wav';
       path += normalizeFilename(;

   var success = item.exportToFile(path);
   if (!success)
       errors += 1;
   fl.trace(displayPath(path) + ': ' + (success ? 'OK' : 'Error'));

fl.trace(errors + ' error(s)');

How to use the script to export sound files:

  1. Save the code above as a .jsfl file on your computer;
  2. Open a .fla file with Adobe Animate;
  3. Select ‘Commands’ → ‘Run Command’ from the top menu and select the script in the dialogue that opens;
  4. Now another dialogue file pops up for selecting export destination directory.

And done! You should now have WAV files in the specified directory. What’s left to do is convert them to, for example, MP3’s, OGG, or AAC.

How To Use MP3s In Flash To HTML5 Convertions

The good old MP3 format is back, as some patents have expired and now every browser can decode and play MP3’s. This makes development a bit easier since finally there’s no need to prepare two separate audio formats. Previously you needed, for instance, OGG and AAC files, while now MP3 will suffice.

Nonetheless, there are two important things you need to remember about MP3:

  • MP3’s need to decode after loading, what can be time-consuming, especially on mobile devices. If you see a pause after all your assets have loaded, then it probably means that MP3’s being decoded;
  • gaplessly playing looped MP3’s is a little problematic. The solution is to use mp3loop, about which you can read in the article posted by Compu Phase.

So, Why Should You Convert Flash To JavaScript?

As you can see, Flash to JavaScript conversion is not impossible if you know what to do. With knowledge and skill, you can stop struggling with Flash and enjoy the smooth, entertaining games created in JavaScript. Don’t try to fix Flash — get rid of it before everyone is forced to do so!

Want To Learn More?

In this article, I was focused mainly on Phaser v2. However, a newer version of Phaser is now available, and I strongly encourage you to check it out, as it introduced a plethora of fresh, cool features, such as multiple cameras, scenes, tilemaps, or Matter.js physics engine.

If you are brave enough and want to create truly remarkable things in browsers, then WebGL is the right thing to learn from the ground up. It’s a lower level of abstraction than various game-building frameworks or tools but allows to achieve greater performance and quality even if you work on 2D games or demos. Among many websites which you may find useful when learning the basics of WebGL would be WebGL Fundamentals (uses interactive demos). In addition to that, to find out more about WebGL feature adoption rates, check WebGL Stats.

Always remember that there’s no such thing as too much knowledge — especially when it comes to game development!

Smashing Editorial
(rb, ra, yk, il)

Source link