Bodymovin json можно создавать и экспортировать из after effects с помощью bodymovin
Поэтапно разберемся во всех нюансах при разработке такого стикера. Начиная с программного обеспечения и заканчивая публикацией в Telegram.
Так что же из себя представляет этот анимированный стикер?
Это собственный формат Telegram — .tgs, который основан на технологии lottie.
Lottie — это движок от Airbnb, который позволяет проигрывать анимации на основе json, созданного с помощью плагина Bodymovin для Adobe After Effects. Такой же плагин существует и для стикеров Telegram и называется аналогично — Bodymovin-TG.
-
или другой векторный графический редактор. + плагин Bodymovin-TG.
Скачиваем с сайта разработчика плагин bodymovin-tg.zxp необходимый для экспорта анимации в формат .tgs.
Для установки потребуется ZXPInstaller — приложение для установки расширений для Adobe.
Открываем ZXPInstaller и переносим плагин в окно программы.
Открываем Adobe After Effects и заходим в раздел настроек — «сценарии и выражения».
Ставим галочку напротив «Разрешить сценариям выполнять запись файлов и осуществлять доступ к сети».
Открываем Adobe Illustrator и выбираем в строке меню «файл» -> «новый».
Во всплывающем окне задаем параметр 512 на 512 пикселей, исходя из требований к размеру стикера.
Для рисования векторного стикера потребуются определенные навыки и знания основных инструментов, поэтому рекомендуется ознакомится с базовыми принципами рисования на сайте Adobe.
Изображение на стикере не должно выходить за края холста.
Существует альтернативный способ (Трассировка) с помощью которого любая картинка превращается в векторную. Будет очень полезно, для быстрого переноса своих растровых изображений в вектор.
В качестве примера возьмем изображение стикера из интернета.
Импортируем изображение в рабочую среду Adobe Illustrator (перенос в окно программы изображения). И проводим указанные действия из видео:
- Трассировка изображения. («Окно» -> «Трассировка изображения»)
- Разобрать. («Объект» -> «Трассировка изображения» -> «Разобрать»)
- Разгруппировать. («Объект» -> «Разгруппировать»)
Трассировка прошла успешно, но алгоритм не всегда точно угадывает форму объекта за элементом. С помощью встроенных инструментов можно устранить эти недостатки.
Выбираем в строке меню «файл» -> «Сохранить как». Сохраняемый тип файла .ai. Во всплывающем окне ставим галочку напротив «Создать PDF-совместимый файл».
Анимация должна быть цикличной , то есть первый кадр анимации должен совпадать с последним кадром.
Использование этих функций в Adobe After Effects приведет к критическим ошибкам при экспорте стикера:
Masks, Mattes, Layer Effects, Images, Solids, Texts, 3D Layers, Merge Paths, Star Shapes, Gradient Strokes, Repeaters, Time Stretching, Time Remapping, Auto-Oriented Layers
Открываем Adobe After Effects и выбираем в строке меню «композиция» -> «Новая композиция».
Во всплывающем окне «Настройки композиции» указываем параметры стикера с учетом официальных требований к анимированным стикерам, такие как:
- Размер — 512 на 512 пикселей.
- Частота кадров — 30 или 60 кадров в секунду. Выбор частоты будет влиять на количество кадров в проекте. Лучше всего выбрать 60 — это обеспечивает большее пространство для анимации.
- Длительность — 3 секунды.
Переносим файл со стикером в рабочую среду Adobe After Effects.
Кликаем правой кнопкой по стикеру, выбираем «создать фигуры из векторного слоя».
Для примера произведем анимацию 3 элементов в стикере.
Разберем подробнее, как анимировать данные элементы в After Effects:
Раскрываем слой "Кривые Sticker" и находим группу с необходимым объектом, быстрее всего это можно сделать кликнув по элементу в окне предпросмотра.
Выбираем пункт "Положение" и активируем его нажав на значок секундомера. После двигаем временную шкалу чуть вперед и передвигаем объект с помощью мыши или вручную, изменяя численное значение "Положение".
Аналогично (1) пункту, за исключением того, что теперь изменять нужно масштаб , а не положение.
Выбираем пункт "Контур" и активируем его нажав на значок секундомера.
Для создания такой анимации потребуется тянуть за «синий квадратик», изменяя тем самым форму объекта и постепенно довести её до требуемого состояния.
Выбираем пункт «Расширения» и находим там плагин Bodymovin.
Отмечаем композицию и выбираем место сохранения нажатием на "троеточие".
После нажимаем на кнопку Render.
Если всё пройдет удачно, в выбранном вами месте появится файл .tgs.
Открываем Telegram и находим в поиске бота @Stickers.
Для начала работы с ним отправляем команду /start.
У всех стикеров в наборе должна быть одинаковая частота кадров. Иначе придется делать два разных пака — для 30 и 60 кадров в секунду.
Отправляем команду /newanimated. После выбираем название и получаем следующую инструкцию:
Спасибо! Теперь отправьте мне, пожалуйста, будущий анимированный стикер — файл в формате TGS, созданный с помощью плагина Bodymovin-TG для Adobe After Effects.
Рекомендуем загружать изображения через десктопное приложение.
Бот Stickers предложит выбрать иконку для анимированных стикеров. Её нужно создать отдельно, но проще всего написать команду /skip, чтобы первый стикер показывался в качестве иконки.
But the fact remains that I enjoy making things colorful and fun to look at.
To that end, I went to film school, I’ve put bread on my plate with photography, and I’ve spent a chunk of my adulthood making motion graphics and working in the trenches of post-production digital effects.
In the world of coding, it’s not an earth-shattering revelation that cool visuals occupy less mental real estate than functionality. This isn’t to ignore the obvious role of UX/front-end work, so much as it is to highlight that the parts of the program that can be seen are a conduit toward the behavior of the program and not an end to themselves. To wit, when the first three weeks of the Flatiron School coalesced into in a coding project, the pinnacles of our group’s visual flourish were a pizza emoji selection arrow and a chunk of text reformatted with ASCII characters.
Part of an undertaking like a coding boot camp is a willingness to surrender some parts of you that preceded the experience. By necessity, to take work as a full-time developer I am foreclosing on motion graphics gigs. Still, after spending so much time married to Adobe After Effects, it seemed a shame that I might need to surrender those skills entirely outside designing the odd CLICK HERE button in Illustrator.
And it turns out I won’t have to!
Wondering about how to apply motion graphics to my code led me to the point of this post, a very, very cool piece of software from Airbnb called Bodymovin.
Bodymovin is an extension for After Effects that allows users to export motion graphics from the After Effects client in JSON format to be used on a webpage through a library called Lottie. Throughout this article, I will use the terms Lottie and Bodymovin interchangably despite their distinct roles (Bodymovin does the exporting, Lottie translates the JSON result) because for my purposes, one can’t function without the other. Other developers can doubtless modify the Lottie library to suit their specific needs, though.
Right, so you can export animations from After Effects as JSON. This begs the question: why do this at all?
After all, it’s not like it’s hard to find jpgs, pngs, movies, or animated gifs of cats on the internet. Clearly humanity has the technology to render all sorts of images just fine and dandy.
Let’s find out from Airbnb directly why Bodymovin exists:
In the past, building complex animations for Android, iOS, and React Native apps was a difficult and lengthy process. You either had to add bulky image files for each screen size or write a thousand lines of brittle, hard-to-maintain code. Because of this, most apps weren’t using animation — despite it being a powerful tool for communicating ideas and creating compelling user experiences. One year ago, we set out to change that.
Let’s start by looking at some bits from the Google Home interface, which uses Bodymovin
Every step of those graphics is drawn by the Home software itself. No files are being called down. As a result, the animations can be shuffled around the interface in whatever way suits the designer with a far greater degree of flexibility than can be obtained with an equivalent movie file. The Google Home onboarding uses approximately 40 different animations. Sending each one to the user would make the Google Home application rapidly grow in size and cause it to be bloated in memory once it was in memory. As Lottie instructions, though, the same animations shrink enormously.
Let’s look again at the Bodymovin logo above:
The JSON of that animation is a little less than 1MB and because it outputs as an SVG (scalable vector graphics) file, it will look crisp and beautiful no matter where it lands. The gif above, by contrast, looks well enough for presentation purposes, but there is obvious artifacting and image degradation that no designer worth his salt would accept in a final product. If I wanted to output a version of the Bodymovin logo as perfect as the SVG animation yielded by Bodymovin’s JSON output, it would be several times larger than the gif above.
As developers we want to be conscious of how the resources we use impact the speed of our code and resulting applications. Even in that first Flatiron School project, the simple act of seeding our database with prototype data — all text — took a few seconds. The utility of Bodymovin is that a motion graphics artist or animator can create animated assets in a program like After Effects without necessarily knowing how to write a line of code, and those assets can be used by designers in the same way as any other code object, because the resulting JSON file will be treated as just another set of instructions to be executed by the app, phone, or browser, i.e. as another code object… And since those objects are not media files, they will invariably be significantly smaller in size than they would be if they were exported from After Effects as media assets.
All a designer or developer needs to do to use the resulting animation is to require the Lottie library (which can be exported along with any Bodymovin animation) on a page where you intend to deploy a BodyMovin asset, and… that’s it.
Lottie can also be insert into existing elements and can thus play with many of the same events and functions that apply to !
Bodymovin is in no way a perfect substitute for the sorts of media assets you can generate with After Effects. Since any effects outside basic transformations are not permitted during Bodymovin exports, artists have to carefully plan their animations to avoid some of the most basic tools.
The individual parts of this animation are pretty basic. There are a pair of solids with the radio wave effect under a time displacement adjustment layer mapped to a radial gradient. There are probably only about a dozen keyframes. The fact that I used effects AT ALL, though, meant the Bodymovin render I got from this was totally unrecognizable. While there is a way to make an animation like this in Bodymovin using just shape layers, the work required would be tenfold. Say goodbye to your fractal noise, your glow, and your luma mattes, folks! While Bodymovin can handle alpha channels to some extent, users have reported that it doesn’t always play nicely with masks — you can’t even feather masks!
In general, if you want a Bodymovin export file to look like the original animation, you’ll want to stick with basic shape layers and transformations. The Lottie homepage has some really useful tutorial on building out projects from Adobe Illustrator to After Effects so the resulting work is transmissible to Bodymovin.
Here’s the full list of what you can and can’t use in After Effects if you want to export your image through Bodymovin. Note in that link that many features are restricted by platform, so what looks awesome on MacBook Air may not load at all on your iPhone! Caveat animator!
Despite the software’s limitations, I’m really excited to use Bodymovin and Lottie to add some beauty and flexibility to the graphics I deploy in my software over the course of my nascent career as a developer.
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations, created using shape layers, exported as JSON data files with Bodymovin and renders them natively on mobile. It is a library that allows a motion designer to create smooth, scalable animations that retain consistency across multiple development environments without the need to spend countless hours/days/weeks endlessly tweaking animations with engineers.
Bodymovin is an After Effects plugin that can be downloaded for free via GitHub. It translates animations based around shape layers in After Effects and exports them to SVG, Canvas, HTML + JS or, when combined with Lottie libraries, iOS and Android. All of this is done through the use of the JSON file format.
Bodymovin extension for After Effects:
Lottie libraries for iOS and Android:
The Lottie libraries below will need to be added to your codebase to utilize the Bodymovin JSONs and implement them in code.
Lottie and Bodymovin players for iOS and Android:
Bodymovin player cross-platform (You can access a settings interface for each composition in the Bodymovin extension interface. One of these settings allows you to save an animation as ‘Demo’ which will create an .html file for your animation which can be viewed in a web browser on both Mac and PC.)
1. Download the Bodymovin extension found here.
3. Open ZXP Installer.
4. Drag bodymovin.zxp into the ZXP Installer window.
5. Once you get the “…installed successfully.” confirmation, hit ‘OK’.
6. Close the app and open Adobe After Effects
First off, we need to have a little talk about workflow. Bodymovin makes certain workflows really easy to translate to code: vector animations are the most beneficial. If your After Effects file is loaded with large amounts of PNGs, PSDs or flattened AI layers, the benefits of Lottie and Bodymovin are greatly reduced. Although bitmaps are supported, using a lot of bitmapped objects will lessen the benefits of the vector workflow. If you are using a large amount of AE or 3rd party plugins, Bodymovin and Lottie won’t be able to support these. If you have a spaghetti mess of expressions that infiltrate every layer of your project and your actual keyframing is minimal, Bodymovin won’t be able to translate much of those expressions to a reasonable workflow. If you are creating animations that are breaking free of the 2D space and venturing into 2.5 or 3D, support of those parameters are limited at this time. Always refer to this section of the Lottie documentation for what features are or are not supported.
Now, that doesn’t mean some of the above isn’t supported, but the ones that may be supported won’t be in a highly advanced stage. Plugins will probably never be supported, expressions will be supported in a more basic form, 3D may be supported over time, PNGs have already been included, but keep in mind, the more you craft your workflow to Bodymovin and Lottie’s strengths, the better results you will get in animation smoothness and small file size.
Launch After Effects and open the animation you want to export with Bodymovin
Go to the ‘Window’ menu, move down to ‘Extensions’ and select ‘Bodymovin’
Once the Bodymovin window comes up, you will want to select what composition you want to export using the radio button on the left side labeled ‘Selected’ and then click on the 3 dots to the right side under the label ‘../Destination Folder’. (A warning here, if you have multiple compositions in the same project that are named the exact same, for example one in a ‘final comps’ and one in ‘old comps’, they will both show up here without reference of where they are in the project. This can cause workflow issues and you may find yourself exporting an outdated comp and pulling out your hair trying to figure out why your JSON is all messed up.)
Give your file a proper name since the default is ‘data.json’ and choose a location to save it, then hit the ‘Save’ button.
If you are not looking at tweaking any other settings hit the ‘Render’ button and let Bodymovin do its thing.
There is a settings icon that you can click on for more options for your comp. The ‘Glyphs’ setting is checked by default but all the others remain unchecked. So far, the only real setting in this window that gets a decent amount of regular use is ‘Demo’ which will create an HTML file for you to play your Bodymovin JSON in a web browser if you don’t have a mobile player to preview what you exported. I encourage you to tinker with the other settings if you feel like they could fix a problem in your workflow.
Bodymovin is doing it’s magic, sit back, relax, have a drink and get ready to preview your vector masterpiece!
Thanks to the amazing and brilliant Adam Plouff, there is a tool that smooths the transition between Illustrator and After Effects called Overlord. Pick up a copy through his website to get started animating faster.
He also makes an amazing plugin called SketchtoAE which can help you when have to work from Sketch source files.
Otherwise if you have work that was created in Adobe Illustrator to be brought into After Effects, you can convert these assets into shape layers, whether you already separated them into layers in Illustrator or not. Below is a quick rundown on how to make this happen.
Select your Illustrator layers in your composition timeline. You can select all the layers at the same time, or just do a chunk at a time, it’s all personal preference and how you like to organize your project.
Bring up the contextual menu, scroll down and choose ‘Create Shapes from Vector Layer’.
After Effects will create new shape layers with all the vector assets and keyframes included at the same time that it will hide the visibility of the old Illustrator layers. You can do a couple things with the old AI layers, you can delete them, you can use the ‘Shy’ layer setting to hide them for now or you can just leave them as they are if the clutter doesn’t bother you. One thing to consider after you have converted the layers is to check your parenting settings, these new vector layers will be paired to the old Illustrator layers and not to their new vector counterparts, so you may want to correct that before deleting anything.
In this example, I have chosen to get rid of the old layers and just work with the new vector versions.
Once the layers have been converted, you will will need to clean the layers up a bit. Select a layer and open it up by hitting the little arrow next to it. Do the same for the ‘Contents’ subset. Depending on the complexity of the vector shape, there could be a number of variations you will find here, but more often you will see ‘Group 1’ as your first content layer. If you open that up, you should see something like the image above. In most cases ‘Path 1’ will be your shape, followed by a nested ‘Group 1’ and ‘Merge Paths’. Two things to consider here, ‘Merge Paths’ doesn’t work in Lottie, so any time this results in a layer conversion, you will need to find a way around it. Secondly, you may find when converting an Illustrator document from an older version, somewhere in the layer you may see a combo like above. What ‘Group 1’ is as well as ‘Merge Paths’ in these instances is a reference to the Illustrator canvas that your vector object is built upon. These are unnecessary carry overs translated into the shape layers. When you come across this combo and it seems to serve no purpose, it’s more than likely this issue and can just be deleted.
Aside from the empty canvas shape groups, you will encounter other ‘Merge Paths’ for letters, numbers, vector objects, etc. When you have located these, modify the shape to replicate the look but eliminate the ‘Merge Paths’ effect. Until Lottie supports this, not eliminating these will result in drawing errors during Lottie playback.
One last thing to consider when optimizing the layers after they have been converted is whether you want to take the time to combine different groups in different layers into the same layer. The bonus from investing time here is you have a more concise and efficient After Effects workflow and could save you some file size in final JSON output file.
When you have made revisions to your animations and got all the kinks worked out, the JSON file is all you will need to hand to the engineering team for implementation.
Before that, however, you will need to preview your animations and make sure they are performing to your standards. Here’s a number of options to get you previewing what you’ve created.
Official-ish iOS Lottie Player In order to use the iOS player you need to have Xcode connected to an Apple Developer account that would allow you to add JSONs to the Xcode project and compile to devices.
One word of caution when evaluating animation playbacks during implementation phases, if you are sending JSON files to your engineers and they are sending you captures back, make sure they are doing it from a tethered device. If they try and capture your animation from the simulator on either Android or iOS, you are going to see a ton of jank and a poor representation of what you created and you may spend days trying to fix something that’s not even broken.
As this list is ever changing with all the updates Lottie gets, it’s best to just check the features website for an easy to read checklist of what you can and can not do with bodymovin’ and the Lottie library.
Lottie — отличный способ экспортировать анимации из After Effects в JSON, сохраняя хорошее качество. В этой статье мы разберёмся, как приступить к работе с этим инструментом и на чём стоит заострить особое внимание.
В 2017 году инженеры Airbnb увидели потенциал анимации на основе JSON и вместе с лидером анимации создали библиотеки iOS и Android, которые смогли бы отображать файлы JSON, которые назвали «Lottie». Вы можете прочитать больше об истории здесь. Разработчики в Airbnb оставили исходный код открытым и создали сообщество GitHub для общения с дизайнерами и инженерами.
LottieFiles — это независимая платформа от Airbnb, на которой дизайнеры могут загружать, тестировать, покупать и выгружать анимации.
Airbnb также являются создателями плагина LottieFiles для After Effects, который работает аналогично Bodymoving и позволяет нам просматривать анимацию, загружать её на платформу LottieFiles, сохранять на компьютере.
Для начала необходимо установить плагин, вы можете использовать Bodymovin или LottieFile.
Я создал для своего логотипа простую анимацию, которая будет отображаться в верхнем меню веб-сайта. Это дрон с вращающимися лопастями, поэтому я импортировал в слои файлы Illustrator, сделал спиральные 3D-слои и повернул их.
Будьте внимательны, не все эффекты поддерживаются этими форматами файлов. На сегодняшний день 3D-слои не поддерживаются. Поэтому, прежде чем делать анимацию, стоит проверить поддержку.
Создание анимации для интернета — это не то же самое, что и создание традиционного видео. Мы должны принять во внимание несколько параметров настройки и форматирования, о которых нам никогда раньше не приходилось думать.
Вот список предложений, которыми делятся создатели Lottie:
- Файлы JSON должны быть как можно более компактными для мобильных продуктов.
- Используйте свои навыки After Effect, чтобы избежать лишних ключевых кадров, например путем родительских функций вместо добавления ключевого кадра на каждом слое.
- Избегайте использования ключевых кадров пути, поскольку они создают очень большой документ из преобразования всей вершины из пути.
- Лучше всего избегать покачивания, автоматической трассировки и аналогичных методов, которые создают большое количество ключевых кадров. Создание такого большого файла может сделать файл JSON очень большим и негативно повлиять на производительность.
- Преобразуйте любой слой Illustrator, EPS, SVG или PDF для формирования слоёв в After Effects, в противном случае это приведёт к ошибке.
- Экспорт в 1X при экспорте файла каждый пиксель на иллюстрации будет переведён в точки для iOS и DPS для Android; вот набор метрик устройств в DPS, которые Google собрала вместе.
- Lottie пока не поддерживает выражения или эффекты.
- Режимы наложения, а конкретно «Умножение», «Экран» или «Добавить» пока не поддерживаются, а также не отображаются с помощью Luma.
- Стили слоёв (тень, наложение, обводка…) пока не поддерживаются; нули могут быть использованы, но для их работы необходимо включить видимость и изменить непрозрачность до 0%.
Импортируйте слои, откройте композицию, выберите все слои, щелкните правой кнопкой мыши и выберите: «Создать» → «Создать фигуру из векторных слоёв».
Это создаст векторные слои, которые не доставят нам хлопот при экспорте в Lottie.
Нам нужно удалить AI-файлы и работать только с векторными слоями.
Я хотел анимировать лопасти в 3D, но поскольку они не поддерживаются, мне пришлось делать это «традиционным способом» и поэтому я симулировал вращение, анимируя размер в X (ширина).
После того, как воссоздать нужную скорость, я создал нулевой объект, чтобы переместить весь логотип и заставить его «взлетать» и «приземляться». При этом используя векторы в положении, чтобы сделать движение более плавным.
Как мы читали ранее, нулевые объекты должны быть превращены в видимые и иметь 0% прозрачности, чтобы работать.
После того, как у меня появилась анимация, я захотел открыть расширение Lottie.
Откроется окно, где вы можете просмотреть анимацию, загрузить её в Lottie-файлы и сохранить на своем компьютере. Для этого вам уже нужно иметь аккаунт в LottieFiles.
Этот способ создания анимации для веб-сайтов действительно интересен, поскольку он сохраняет отличное качество и прост в реализации.
JSON has 100 times smaller file size than GIFs with crystal clear resolution.
How many times have you heard developers saying:
“Let’s not use this GIF the size is way too much. Use some image…or select something from native library!!”
Almost every damn time!
That frustrates me like anything. Still I would bump in my seat to further reduce the GIF size. All that pixel perfect animation with smooth transition, carefully placed keyframe with perfect colour combination right on the highway to hell.
Followed by a desperate ☕ + 🚬 break.
That was life, struggling to get animation fit into my application. Then one fine day a developer friend of mine introduced me to Bodymovin by AirBNB.
And it changed everything.
Now…
Bodymovin is an open source After Effects extension to render your vector animation into .JSON file.
In a simple definition: JSON is Java Script Object Notation which turns your animation into a set of script rather than multiple PNG frames. Developers then copy paste these codes into their iOS, Android, and React Native library that renders After Effects animations in real time. This allows apps to use animations as easily as they use static assets with file size as low as SVGs itself.
• Since it is not a static animation, you have liberty to play around with responses. Like in the example below, Clap icon keeps on clapping the longer you keep hold on it. It is directly responsive to your action unlike GIFs.
•Resolution Free: Since these are SVG based animation you can control their sizes without any fear of loosing the clarity and resolution. Just change Width and Height in the body text code. 💁🏻
Bodymovin is an open source extension so you don’t have to pay any extra dime for it. Here are the steps:
- Download the After Effect Bodymovin extension from here.See I have done the tough job for you already 😎
- Once downloaded, double tap the .dmg file.
3. Drag XZP installer into ‘Application’ folder.
4. Check your After Effects extension folder to confirm. Now all set. 👍
6. Make sure your animation doesn’t contain complex features like Color Inversion, Stylize, Simulation effect like Rainfall, Shatter, Wave, Drizzle, Bubble etc. You can however use basic features like masking and layer properties etc.
7. I have made one simple loader animation to help you guys understand how this works. Remember, use basic features because they are more than enough to get pretty and light animation. You can still use complex features, no restriction to that, but old OS might not be able to run it. So let’s be on the safer side.
8. Once your animation is done. Go to Window > Extensions > Bodymovin
9. In the Bodymovin extension window, there are few options like ‘change destination folder, select the composition you want to render, change the settings’ etc. Go to ‘Settings’ as highlighted below:
In the settings, selected the following options:
• Glyphs: Select this option if there is any text in design.
• Demo: Always select this option. You can directly play the .html file from export folder into a web browser.
• AVD: Thats’s the XML file used by Android developers.
10. Voilla. Here is your .json, .html and .xml file. Send them to your developer & watch Netflix.
Now let’s go put some kickass animation into your app.
Gracias 🙏🏼
Читайте также: