Adobe

decor

Web Platform Team Blog

Making the web awesome

CSS animations and transitions performance: looking inside the browser

You’ve probably used CSS Animations or CSS Transitions in a project. (If not, check out CSS-Trick’s almanac entries on animations and transitions.) Some of your animations might have performed smoothly. Other might have appeared choppy. Do you wonder why?

In this article, we’ll explore how browsers handle CSS Animations and CSS Transitions, so you can develop intuition around whether an animation is likely to perform well — before writing any code! With this intuition, you’ll be able to make design decisions that play well with the browser and result in silky smooth user experiences.

Browser Internals

Let’s pop the hood of the browser, and look around. Once we understand how it works, we can drive it better.

Modern browsers typically have two important threads of execution. These threads work together to render a web page:

  • The main thread
  • The compositor thread

Typically, the main thread is responsible for:

  • Running your JavaScript.
  • Calculating your HTML elements’ CSS styles.
  • Laying out your page.
  • Painting your elements into one or more bitmaps.
  • Handing these bitmaps over to the compositor thread.

Typically, the compositor thread is responsible for:

  • Drawing bitmaps to the screen via the GPU.
  • Asking the main thread to update bitmaps for visible or soon-to-be-visible parts of the page.
  • Figuring out which parts of the page are visible.
  • Figuring out which parts are soon-to-be-visible when you’re scrolling.
  • Moving parts of the page when you scroll.

The main thread can be busy for long periods of time running your JavaScript or painting a large element. While it’s busy, it’s not responsive to user input.

On the other hand, the compositor thread tries to stay extremely responsive to user input. The compositor tries to redraw the page 60 times per second when the page is changing, even if the page is incomplete.

For example, when the user scrolls a page, the compositor thread asks the main thread to update the bitmaps for newly visible parts of the page. However, if the main thread doesn’t respond quickly enough, the compositor doesn’t wait. The compositor draws the parts of the page it has so far and draws white elsewhere.

The GPU

I mentioned the compositor thread draws bitmaps to the screen using the GPU. Let’s quickly go over the GPU.

The GPU is a chip found in most phones, tablets, and computers today. It’s extremely specialized, meaning it’s really good at certain things, and it’s not that great at others.

GPUs are really fast at:

  1. Drawing to the screen.
  2. Drawing the same bitmap over and over again.
  3. Drawing the same bitmap in a different position, rotation, or scale.

GPUs are relatively slow at:

  1. Loading bitmaps into their memory.

transition: height

Now that we have a rough idea of the software and hardware running our page, let’s look at how the browser’s main thread and compositor thread work together to perform a CSS Transition.

Suppose we’re transitioning an element’s height from 100px to 200px, like so:


div {
    height: 100px;
    transition: height 1s linear;
}

div:hover {
    height: 200px;
}

The main thread and the compositor thread will perform operations according to the timeline diagram below. Note that operations in orange boxes are potentially time-consuming. Operations in blue boxes are quick.

animate-height-2x

As you can see, there are lots of orange boxes, meaning the browser has to work pretty hard! This means the transition might be choppy.

In every frame of the transition, the browser has to perform layout, painting, and uploading new bitmaps to the GPU. As we learned, loading bitmaps into GPU memory can be a relatively slow operation.

The reason the browser has to work so hard every frame is because the contents of the element keep changing. Changing an element’s height may cause its child elements to also change in size, so the browser has to perform layout. After layout, the main thread has to regenerate the bitmap for the element.

transition: transform

So, height can be somewhat expensive to transition. Is there something cheaper?

Suppose we’re scaling an element from half size to full size. Also suppose we’re using the CSS transform property to scale it and the CSS transition property to animate the scaling, like so:


div {
    transform: scale(0.5);
    transition: transform 1s linear;
}

div:hover {
    transform: scale(1.0);
}

Let’s look at the timeline diagram for this case:

animate-transform-2x

We see a lot less orange this time, meaning the animation will probably be smooth! So, how is animating an element’s transform different than animating its height?

By definition, the CSS transform property does not change the layout of an element or the elements around it. It affects the element as a whole- it scales the whole element or rotates the whole element or moves the whole element.

This is great news for the browser! The browser only has to generate the bitmap for the element and upload it to the GPU at the start of the animation. After that, the browser doesn’t have to do any more layout, painting, or bitmap uploading. Instead, the browser can leverage the GPU’s special ability to draw the same bitmap in a different position, rotation, or scale quickly.

Design Decisions

So, does this mean we shouldn’t animate an element’s height? No. Sometimes it’s exactly what your design warrants, and the animation could be fast enough. Maybe your element is isolated, and doesn’t cause other parts of the page to be laid out again. Maybe your element is simple to repaint, and the browser can do it quickly. Maybe your element is small, and the browser only has to upload a small bitmap to the GPU.

Of course, if you can animate a “cheaper” property like CSS transform instead of a more expensive property like CSS height, and there is no impact on your design vision, do that. For example, lets say your design involves a button that reveals a menu when tapped. Instead of animating the menu’s CSS top or height properties to reveal it, try animating the element’s CSS transform property for a similar or identical effect.

The CSS properties that are particularly fast to animate include:

This list is somewhat limited today, but as browsers advance, you’ll see more and more CSS properties becoming fast to animate. Also, don’t discount the current list. You might be surprised at just how many rich effects you can create by combining these properties. Get creative!

CSS Shapes geometry: discussed and demo’d

Flowing text around shapes shouldn’t be burdensome. If you have one continuous string of text, why not wrap it like a ribbon that can smoothly conform to a shape? The engineers who are implementing the CSS Shapes Module Level 1 spec are bringing that capability to the web platform.

Sara Soueidan experiments with creating non-rectangular layouts with CSS Shapes. Her articles spark ideas for creating magazine-like layouts and the creativity of taking shapes further with animation.

Hans Muller’s latest blog on the subject, A Simpler Algorithm for CSS Shapes Level 1, takes the time to break down what is happening on the implementation level.

The shape-margin property expands the polygon by the specified radial distance.

How does the shape-outside property flow content around a shape? Hans explains the fundamental geometry involved, and provides a demo that makes these concepts come to life.

Happy birthday, web, and many more

The web is 25 years old today. In its short existence it has transformed the way we play, learn, work and connect with each other. And yet, this is just the beginning. The web has the potential to transform the creative process.

Sir Tim Berners-Lee used his creativity when on March 12, 1989 he submitted his proposal for the World Wide Web and gifted it to the world as an open and free standard.

Today, two people in five have access to the web. That’s amazing, but we need the whole world to have equal, uncensored access. We must safeguard our privacy and personal freedom. We need to make sure that the web avoids fragmentation and remain a truly global resource. We all have a role to play in making sure we get the web we want and the web we deserve. As Sir Tim said, “This is for everyone.”

The web has made our planet more connected than ever. It has helped spread information, knowledge and ideas that can make the world a better place.

Within us all is the power to make a difference through our imagination and creativity.

We are all born creative. We all start as fearless explorers banging on pots and pans. We are all artists who have created masterpieces with our fingers dipped in paint.

More than ever we need creativity to solve our most challenging problems. And the web can eliminate the friction in the creative process.

The creative process is fundamentally collaborative and the web can enable connected creativity. The web can make it easier to be inspired by discovering and building on ideas from your neighbor next door or from across the world.

You can do truly remarkable things today on the web. And yet, it needs to be an even more expressive canvas. We’ve barely scratched the surface.

At Adobe, we’re passionate about building the best tools in the world for creative people. We believe in the potential for the web to transform the creative process. We’re looking forward to continue contributing to this grand enterprise.

The web has come a long way in its short existence, but there is so much more to do.

Let’s make it happen.

Add Shape and Depth to Your Layout with Photoshop and CSS Shapes

In the current Webkit implementation of the CSS Shapes specification, we’ve added support for shape-outside  using an image as a value. In this case, rather than defining the shape with a basic-shape function, the shape is computed from the image’s alpha channel, with the opacity threshold being configurable with shape-image-threshold. By using an image with a transparent background, you can use CSS Shapes to flow text around the arbitrary shape defined by your image.

The default behavior is to define the shape as the area(s) of the image greater than 0% opacity so even semi-transparent areas, such as drop shadows, will be part of the shape. In this article, I’ll walk you through creating an image and defining a drop shadow in its alpha channel using Photoshop and then how to use it with CSS Shapes to create depth & contour to this simple encyclopedia layout.

 gears-first-page

 Defining a Shape in the Alpha Channel with Photoshop

We’ll start by opening this simple image in Photoshop.

1. Create a new layer and name it ‘shadow’. We’ll be creating the drop shadow on this layer, so move it beneath the main image.

Create a New Layer

2. Fill the layer with black and set the fill opacity to 50%

Set Layer Fill & Opacity

3. With the shadow layer selected in the Layers panel, select the image with the Quick Selection tool. Click the Refine Edge button and set the Feather to 5px.

Soften the edges of the selection

4. Create a new Layer Mask. With the Move tool, adjust the shadow layer down and to the right.

Switch to the Channels panel and see the new alpha channel that has been created from the layer mask. This will be the shape around which text will flow when used with CSS Shapes.

Alpha Channel

Save the image as a PNG.

Wrapping Text Around Images with CSS Shapes

First, we’ll take our original page layout and modify to wrap around the unshadowed image.


#gears
{
    float: left;
    shape-outside: url("gears.png");
}
 ...

Since the original image had a transparent background, the shape is defined as the outline of the gears. Using shape-outside, we see the text wrap around the gears like this:

Using shape-margin, you can specify how close you want the text to wrap next to your image.

By default, the shape-margin is none, which in this case, wraps the text a little too close to the gears. We can adjust this accordingly:


#gears
{
    float: left;
    shape-outside: url("gears.png");
    shape-margin: 10px;
}

Much better:

But rather than setting a shape-margin: 10px;, I’d like to use the drop shadowed image we create above and allow the shadow in the alpha channel to define the contour of the shape.


#gears
{
    float: left;
    shape-outside: url("gears-dropshadow.png");
}
...

Resulting in this:

That’s it. In just a few simple steps, we added depth and richness to an otherwise flat and boxy layout using this cool new CSS feature.

If you’re curious about how exactly we calculate the shape from images, read about the algorithm for determining the first fit location for an image shape in Hans Muller’s blog.


 
 
The text in this example was excerpted from Wikipedia:
Gear. (2014, March 9). In Wikipedia, The Free Encyclopedia. Retrieved 20:41, March 10, 2014, from http://en.wikipedia.org/w/index.php?title=Gear&oldid=598819607

CSS Regions polyfill – better, smarter, fuller

We first started work on a CSS Regions prototype to give designers and developers a seamless and flexible way to flow content inside a chain of boxes. As the feature gained visibility, it became clear that people wanted to experiment outside the WebKit-based browsers. So about one year ago, we created a rather simple polyfill supporting only basic functionality. Today, we would like to introduce a much-improved CSS Regions polyfill library, created by Francois Remy.

What’s new

What’s new? Basically everything the new polyfill was re-written from scratch to make it more flexible and feature rich. Under the hood, it is based on a general-purpose CSS parser. This means it’s more robust and less likely to produce unexpected results if your CSS is odd-looking (minified, uglyfied and so on).

The most readily apparent difference from the old polyfill is that it drops the support for the −adobe− prefix and instead only supports the standard, non-prefixed form of the properties and APIs. If your stylesheets are future-proofed with the standard, non-prefixed syntax, the new polyfill is essentially a drop-in replacement: you don’t need to do anything else! :) Also, all CSS properties are supported: along with flow−from and flow−into, region−fragment, break−before and break−after are supported (Keep in mind, Safari uses the old syntax for forced breaks inside regions, −webkit−region−break−before and −webkit−region−break−after).

Another notable addition is the support for the Regions CSSOM. This covers the NamedFlow interface, additions to the Element interface corresponding to the Region interface and support for the NamedFlow events (regionoversetchange and regionfragmentchange).

Unlike the old polyfill that required the Regions-specific code to be inlined within the HTML, the new polyfill fully supports external stylesheets. It also automatically updates the layout when the DOM is changed through JavaScript or when the viewport size changes through resizing or device rotation.

Also, unlike the old polyfill, the new polyfill doesn’t require the regions to have their size explicitly set.

What’s the catch?

This is a polyfill. It’s not the real deal and has some gotchas you should be aware of.

First of all, interactive content like form elements, contentEditable elements or user-interaction pseudo-classes (for example, :active, :hover) and JavaScript event listeners are something of a shot in the dark. The polyfill actually clones the contents of the named flow to move them through regions. This will likely cause interactive content to work in unexpected ways. Another effect of the content cloning is with the CSS cascade. The new DOM structure could make some selectors not apply anymore or new selectors to apply where they wouldn’t before.

This polyfill is doing the layout asynchronously. So, the user may experience content flickering, especially if scrolling before the page layout is complete. Especially with more complex layouts, auto-sizing can behave differently than a browser-native implementation.

Another missing piece is support for region styling – neither the standard ::region() pseudo-functional syntax nor the old and no longer standard @region syntax.

In terms of CSSOM, the NamedFlow.getRegionFlowRanges() is not implemented. Furthermore, the timing of the NamedFlow events is not guaranteed to be the same as a native, standards-compliant implementation. This means some events could be fired more often or with a delay when compared to a native, standard-compliant implementation.

Demo time

If you want to see the new polyfill in action you can check out the Regions samples hosted on CodePen. Where possible, we’ve converted the samples to render with the polyfill if the browser doesn’t support CSS Regions natively. Also, two important demos showing some of the major use cases of CSS Regions – the National Geographic Orphan Elephants demo and the Adaptive UI demo – are now polyfill-enabled so you can enjoy them on any browser, not just Safari.

How to get it

You can grab a copy from Francois Remy’s GitHub repository. There you will also find extensive documentation of what the polyfill does and how it does it.

Feel free to grab a copy, give it a run and, if something bugs you, don’t hesitate to file an issue or send out a pull request.

CSS Regions polyfill – better, smarter, fuller

We first started work on a CSS Regions prototype to give designers and developers a seamless and flexible way to flow content inside a chain of boxes. As the feature gained visibility, it became clear that people wanted to experiment outside the WebKit-based browsers. So about one year ago, we created a rather simple polyfill supporting only basic functionality. Today, we would like to introduce a much-improved CSS Regions polyfill library, created by Francois Remy.

What’s new

What’s new? Basically everything the new polyfill was re-written from scratch to make it more flexible and feature rich. Under the hood, it is based on a general-purpose CSS parser. This means it’s more robust and less likely to produce unexpected results if your CSS is odd-looking (minified, uglyfied and so on).

The most readily apparent difference from the old polyfill is that it drops the support for the −adobe− prefix and instead only supports the standard, non-prefixed form of the properties and APIs. If your stylesheets are future-proofed with the standard, non-prefixed syntax, the new polyfill is essentially a drop-in replacement: you don’t need to do anything else! :) Also, all CSS properties are supported: along with flow−from and flow−into, region−fragment, break−before and break−after are supported (Keep in mind, Safari uses the old syntax for forced breaks inside regions, −webkit−region−break−before and −webkit−region−break−after).

Another notable addition is the support for the Regions CSSOM. This covers the NamedFlow interface, additions to the Element interface corresponding to the Region interface and support for the NamedFlow events (regionoversetchange and regionfragmentchange).

Unlike the old polyfill that required the Regions-specific code to be inlined within the HTML, the new polyfill fully supports external stylesheets. It also automatically updates the layout when the DOM is changed through JavaScript or when the viewport size changes through resizing or device rotation.

Also, unlike the old polyfill, the new polyfill doesn’t require the regions to have their size explicitly set.

What’s the catch?

This is a polyfill. It’s not the real deal and has some gotchas you should be aware of.

First of all, interactive content like form elements, contentEditable elements or user-interaction pseudo-classes (for example, :active, :hover) and JavaScript event listeners are something of a shot in the dark. The polyfill actually clones the contents of the named flow to move them through regions. This will likely cause interactive content to work in unexpected ways. Another effect of the content cloning is with the CSS cascade. The new DOM structure could make some selectors not apply anymore or new selectors to apply where they wouldn’t before.

This polyfill is doing the layout asynchronously. So, the user may experience content flickering, especially if scrolling before the page layout is complete. Especially with more complex layouts, auto-sizing can behave differently than a browser-native implementation.

Another missing piece is support for region styling – neither the standard ::region() pseudo-functional syntax nor the old and no longer standard @region syntax.

In terms of CSSOM, the NamedFlow.getRegionFlowRanges() is not implemented. Furthermore, the timing of the NamedFlow events is not guaranteed to be the same as a native, standards-compliant implementation. This means some events could be fired more often or with a delay when compared to a native, standard-compliant implementation.

Demo time

If you want to see the new polyfill in action you can check out the Regions samples hosted on CodePen. Where possible, we’ve converted the samples to render with the polyfill if the browser doesn’t support CSS Regions natively. Also, two important demos showing some of the major use cases of CSS Regions – the National Geographic Orphan Elephants demo and the Adaptive UI demo – are now polyfill-enabled so you can enjoy them on any browser, not just Safari.

How to get it

You can grab a copy from Francois Remy’s GitHub repository. There you will also find extensive documentation of what the polyfill does and how it does it.

Feel free to grab a copy, give it a run and, if something bugs you, don’t hesitate to file an issue or send out a pull request.

Designers Who Code Meetup in SF

Are you a designer who also codes? We’ve got just the meetup for you!  The Designers Who Code meetup group will be hosted at Adobe’s SF office on Wed, March 5 at 6pm. Join us for an evening of good talks, networking, drinks and fun. The line-up of speakers includes Divya Manian and CJ Gammon:

There will also be tables set up for folks to mingle and meet with the teams behind Edge Tools + Services. Plus, we’ll be holding a raffle for Adobe Creative Cloud memberships.

Event Schedule
6:00 – 7:00: Food, Drinks, Networking & Product Exploration
7:00 – 8:15: Talks
8:15 – 8:30: Speaker Q&A
8:30 – 9:00: Networking

Web + Wow: An Exploration of the Web as a Medium
with CJ Gammon

The web is becoming an increasingly mixed medium with the growing list of technologies we have at our disposal. In this session we will discuss rich web experiences and different techniques used to achieve them. We will also cover new and upcoming web features and explore how these may change the way we create rich web content in the future.

Unmasking the GPU: Using Hardware Acceleration Correctly in CSS
with Divya Manian

Browsers have been offloading more and more of newer CSS features to be processed by the GPU. This is a new unmapped territory which makes it more important to understand how and when browsers do this, so you can prevent disruptive behaviour for your users that may even end up in crashing their computers. Learn which CSS properties are accelerated, how and what you can do to make sure you know when and how to use them correctly to ensure smooth experience.

Lightning Talks
Have something interesting you’d like to talk about that you can present in five minutes or less? Reach out to us with a title of your topic and a brief description on what it encompasses to see if it’d be a good fit for this event.

For more information and to RSVP, go to the Designers Who Code Meetup page.

Improving your site’s visual details: CSS3 text-align-last

In this post, I want to give a status report regarding the text-align-last CSS3 property. If you are interested in taking control of the small visual details of your site with CSS, I encourage you to keep reading.

The problem

First, let’s talk about why we need this property. You’ve probably already seen many text blocks on pages that don’t quite seem visually correct, because the last line isn’t justified with the previous lines. Check out the example paragraph below:

Example of the CSS3 text-align-last property

In the first column, the last line isn’t justified. This is the expected behavior, when you apply the ‘text-align: justify’ CSS property on a container. On the other hand, in the second column, the content is entirely justified, including the last line.

The solution

This magic is the ‘text-align-last’ CSS3 property, which is set to justify on the second container. The text-align-last property is part of the CSS Text Module Level 3 specification, which is currently a working draft. The text-align-last property describes how the last line of a block or a line right before a forced line break is aligned when ‘text-align’ is ‘justify’, which means you gain full control over the alignment of the last line of a block. The property allows several more options, which you can read about on WebPlatform.org docs, or the CSS Text Module Level 3 W3C Specification.

A possible use case (Added April – 2014)

After looking at the previous example (which was rather focusing on the functionality of the property), let’s move on to a more realistic use case. The feature is perfect to make our multi-line captions look better. Check out the centered, and the justified image caption examples below.

centertext_align__simple_justify

And now, compare them with a justified, multi-line caption, where the last line has been centered by text-align-last: center.
text_align_last_center

I think the proper alignment of the last line gives a better overlook to the caption.

Browser Support

I recently added rendering support for the property in WebKit (Safari) based on the latest specification. Dongwoo Joshua Im from Samsung added rendering support in Blink (Chrome). If you like to try it out in WebKit, you’ll need to make a custom developer build and use the CSS3 text support build flag (--css3-text).

The property is already included in Blink’s developer nightlies by default, so after launching your latest Chrome Canary, you only need to enable ‘Enable experimental Web Platform features’ under chrome://flags, and enjoy the full control over your last lines.

Developer note

Please keep in mind that both the W3C specification and the implementations are under experimental status. I’ll keep blogging about the feature and let you know if anything changes, including when the feature ships for production use!

Using blend modes in HTML Canvas

collage

Canvas blending is an HTML feature for designers and web developers. In this blog post, I  present the syntax and some use cases where blend modes are particularly useful.

What are blend modes?

To put it simply, blend modes are ways of combining two graphic objects using special mathematical formulas.

Recently, blend modes have landed in HTML 2D Canvas. The feature is enabled in Apple Safari, Mozilla Firefox and Google Chrome.

At a first glance, blend modes seem to be no different than transparency, but in reality, the results achieved with blending are much more expressive than using simple opacity. In practice, blending is generally used together with transparency.

If you want to read more about each of the blending operations, you can check out How To: An Explanation of Illustrator’s Blending Modes by Sara Froehlich.

Using canvas blending

To use blend modes in canvas,  set the globalCompositeOperator property of the Context 2D Canvas, as follows:

 Javascript |  copy code |? 
1
// Get the canvas element. "cvs" is the id of the html canvas element.
2
var canvas = document.getElementById("cvs");
3
 
4
// Get the Context object.
5
var context = canvas.getContext("2d");
6
 
7
// Set the blending operation.
8
context.globalCompositeOperation = "multiply";

After this block is executed, any graphic elements drawn on the canvas are blended using the “multiply” blend mode.

In the first example, there are two assets: a raindrop pattern and a picture of a building. We’d like to make the building look as if it’s reflected in the raindrop.

Check out this Pen!

To achieve this result, we first draw the raindrop picture. Once this operation is finished, we set the blendMode of the canvas to soft-light.

In the next step, we draw the second image. Click the button to preview the effect. As you can see, the result looks like a reflected building.

Finally, we add one more effect: we blend the result with a linear gradient. All we have to do is create and draw the gradient in the canvas, since the blending operation is already set. You can see the result by clicking on the button.

After finishing these tasks, we want to prevent any further elements drawn into the canvas from blending.

This means we have to clear the blending operator, as follows:

 Javascript |  copy code |? 
1
context.globalCompositeOperation = "source-over";

The next demo showcases two of the most extensively used blend modes: screen and multiply.

Imagine the following scenario: you are developing a game where a character is trapped in a dungeon. The dungeon consists of a dark cavern. The player needs a light source. Let’s see how we can achieve these results with blending:

The following pen shows this result. Use the W, A, S, D keys to travel around the map. Press any other key to intensify the light source.

Check out this Pen!

Here, we use the multiply blend mode to darken the map: this is done by drawing the actual map as an image, followed by setting the blend mode of the canvas context to multiply. Next, a gray rectangle is drawn on top of the initial image. The darkening effect is now complete.

The second use of blending is to simulate the light emitted from the character in the dungeon. For this, we use a radial gradient, from transparent to yellow. This gradient is now blended with the backdrop using the “screen” blend mode operation, thus simulating the effect of a torch.

The next example shows how fog effects can be simulated using blend modes. If you hover over the next pen, you will see how fog is dynamically added to the canvas. How is this achieved?

Check out this Pen!

Radial gradients from transparent to white are added to the photo, using the soft-light blend mode.

In general, when using blend modes, the result can sometimes be too intense. In order to temper this, it’s a common pattern to blend with transparency. The trick is to tune the blending result by setting opacity on the layer that is blended. As shown in this example, varying the opacity of the gradient’s color actually determines the density of the fog. You can set the fog density through the slider at the bottom of the page and observe how the result if more powerful for higher opacity.

Here’s another effect that can be obtained with canvas blend modes: let’s say you are designing a game where the player controls a character. If the character has low hit points, you can flash the player’s screen, with red, as a warning sign. In the next example, this is done by drawing a red rectangle on top of the whole canvas, using the overlay blend mode.

Check out this Pen!

This shows the power of blend modes. You can click the radio buttons to switch the way the overlay rectangle is drawn. The blending result is clearly better than the one using only transparency.

My last example is a solution to the following problem: you have a pattern and you want to draw a group of elements, and blend this whole group with the pattern. If you set the blend mode of the canvas and start drawing the elements of the group one by one, they blend with each other, causing an undesirable result.

Check out this Pen!

Thankfully, as shown in the following pen, there is a solution for this problem: In this example, we have a t-shirt pattern and a robot. The robot is made of a group of elements.

To blend the robot with the t-shirt pattern, this is what you have to do:

Draw the robot in a new canvas. This is achieved by creating a new canvas element. When we’re done drawing the robot, we set the blend mode on our original canvas and draw the newly created canvas on the original one, as follows:

 Javascript |  copy code |? 
01
// This creates a new canvas where we’ll draw the robot.
02
var layerCanvas = document.createElement("canvas");
03
var layerContext = layerCanvas.getContext("2d");
04
 
05
// Actually draw the robot.
06
layerContext.fillStyle = "purple";
07
layerContext.beginPath();
08
layerContext.arc(50, 50, 40, 0, 2 * Math.PI);
09
layerContext.fill();
10
layerContext.fillStyle = "navy";
11
layerContext.fillRect(5, 35, 90, 30);
12
layerContext.fillStyle = "purple";
13
layerContext.fillRect(20, 40, 20, 20);
14
layerContext.fillRect(60, 40, 20, 20);
15
 
16
// Set the blend mode of the original canvas
17
context.globalCompositeOperation = "overlay";
18
 
19
// Blend the robot with the pattern.
20
// Drawing the newly created canvas on top of the original one.
21
context.drawImage(layerCanvas, 100, 70);

Conclusions

In this blog post, we show the usage of canvas blend modes and provided some examples, most of which can be used in designing games or photo editing. Finally, we highlight the differences that opacity makes when used with blending, and why blending is different than simple transparency.

We’d love to hear from you, either if you have questions, demos or thoughts on this feature.

Codepens

Here are the code samples used in this blog post:

  1. Example 1: Reflected building.
  2. Example 2: Light effect.
  3. Example 3: Fog effect.
  4. Example 4: Flashing screen.
  5. Example 5: Blending groups. T-shirt design.

Adobe SXSW 2014 Creative Camp

Adobe is traveling to SXSW for our Annual Creative Camp, Friday March 7th at the Radisson Town Lake, Riverside Ballroom. This year we have five sessions on topics shaping the modern web. Relax in the Typekit pop-up library, a hang-out with 65+ specially-curated design books. Plus, you’ll need your fuel to make it through SXSW and we’ve got you covered all day with lunch, and snacks galore – flavored popcorn, mini-burgers and petit BLT’s plus a happy hour during our final session of the day.

Here’s our session line up:
 
What Do We Build Next? 11:00 – 12:00
 
Get behind the scenes at Adobe and learn how our product development teams go from just an idea to a functional prototype ready for testing with real users in a matter of weeks for their newest web authoring tools. Devin Fernandez, Principal Product Manager, and Winsha Chen, Senior Computer Scientist will show examples of real projects under development right now.
 
5 Things Developers Need to Know About Design 12:30 – 1:30
 
In this session you will learn with Adobe Evangelist Paul Trani the techniques designers use as well as the things they wish every developer knew about design. Understanding these 5 things will not only make you better at design, it will help you work better with designers. We’ll also be serving lunch during this session so make sure you come early to grab a sandwich and get a seat.
 
Rich Web Experiences & the Future of the Web 2:00 – 3:00
 
We’re reaching a point where ideas we could only dream of in the past from interactive film to global multiplayer 3D gaming can become a reality, all living inside of your browser. We’ll explore inspiring examples of how the web can be used to create rich media experiences and what’s possible in the future with Adobe Creative Technologist CJ Gammon.
 
The Onions of Interactive Infographic Design 3:30 – 4:30
 
Interactive infographics make it possible for you to truly capture your audience and engage with them in a manner that simply is not possible when merely citing dry facts or statistics. This session will cover the value of creating animated, interactive infographics with HTML your readers care about using Adobe Edge Animate with Product Manager, Sarah Hunt.
 
The Ultimate Developer’s Tool: Theory & Discussion 5:00 – 6:00
 
What do iOS, Android, and the Internet all have in common? They were all built using source code editors driven. But what qualities are needed in a modern code editor? Enjoy some cold beer and snacks while you engaging in a discussion with Senior Product Manager, Jonathan Dunlap, on how we can use our present knowledge to build the ultimate source code editor.

These sessions are official SXSW events. A badge is required to attend and no registration needed.