sadr0b0t / babbler-robots

0 stars 1 forks source link

Анимация SVG в React #3

Open sadr0b0t opened 7 years ago

sadr0b0t commented 7 years ago

Выбрать способ анимации в Реакте. Требуется плавное перемещение и изменение размера точки - рабочий инструмент. Желательно, с поддержкой родных механизмов React.

выношу отдельно отсюда https://github.com/1i7/babbler-robots/issues/2

sadr0b0t commented 7 years ago

https://github.com/1i7/babbler-robots/issues/2#issuecomment-282876503

По анимации - предварительно варианты

react-svgpathplayer - анимация путей SVG (использует Snap.svg) http://saschwarz.github.io/react-svgpathplayer/ https://github.com/saschwarz/react-svgpathplayer

Анимация с React+SVG. Требуется, например, анимировать перемещение точки - это изменение координат X и Y у кружочка.

чел задаётся аналогичным вопросом http://stackoverflow.com/questions/35647928/transition-animation-using-react-and-svg

и сам себе отвечает http://bl.ocks.org/herrstucki/9205257

еще какая-то анимация в react-native (похоже, прям покадрово рисуют) http://browniefed.com/blog/react-native-morphing-svg-paths-with-react-art/

Паттерны React https://habrahabr.ru/post/309422/

интересный момент про Function as children+Render callback - проверить, имеет ли отношение к анимации

Использование функций как потомков требует дополнительного внимания с вашей стороны, чтобы можно было извлечь из них пользу. {() => { return "hello world!»}()} Однако, они могут придать вашим компонентам супер силу, такая техника обычно называется рендер-коллбэк. Эта мощная техника используется в таких библиотеках как ReactMotion. Когда вы применяете ее, логика рендера может управляйся из родительского компонента, вместо того, чтобы полностью передать ее самому компоненту.

sadr0b0t commented 7 years ago

SVG Animation and CSS Transforms: A Complicated Love Story https://css-tricks.com/svg-animation-on-css-transforms/

из последнего ссылка на библиотеку для анимации с JS

GreenSock's GSAP https://greensock.com/gsap

sadr0b0t commented 7 years ago

Еще про анимацию

https://sarasoueidan.com/blog/svg-transformations/

Animating transform SVG transformations can be animated, just like CSS transforms can be. If you’re using the CSS transform property to transform the SVG, you can animate the transformation using CSS animations and transitions just like you would animate CSS transforms on HTML elements.

sadr0b0t commented 7 years ago

Короче, вижу три подхода к анимации.

  1. Стантартный - через CSS Transition Какой-то мутный способ вроде через навешивание и удаление CSS-блоков, требуется добавлять специальные теги.

Много разных инструкций с разъяснениями

Animation Add-Ons https://facebook.github.io/react/docs/animation.html

React animations for a single component http://unitstep.net/blog/2015/03/03/using-react-animations-to-transition-between-ui-states/

UI Animations with React — The Right Way https://medium.com/@joethedave/achieving-ui-animations-with-react-the-right-way-562fa8a91935#.cgtrt88zp

ReactJS - Animations, Step 1 - Install React CSS Transitions Group http://www.tutorialspoint.com/reactjs/reactjs_animations.htm

Как реализовать анимации в React? https://toster.ru/q/294137

Если вам нужно плавно скрыть элемент - CSSTransitionGroup вполне подойдет. Прочтите документацию - https://facebook.github.io/react/docs/animation.html (не вижу смысла здесь ее переписывать). В общем принцип работы таков - компонент CSSTransitionGroup сохранит элемент в DOM на время перехода (анимации) и сразу после ее завершения - удалит (если речь об удалении DOM).

ReactJS Animation done in two ways The React way The JavaScript way http://www.chloechen.io/react-animation-done-in-two-ways/

Произвольное свойство проанимировать таким способом, насколько понимаю, не получится.

еще какой-то прибамбас со стандартного сайта, но для React-native (не ясно, насколько совместим с обычным реактом)

Animations https://facebook.github.io/react-native/docs/animations.html

React Native Animations Using the Animated API https://medium.com/react-native-training/react-native-animations-using-the-animated-api-ebe8e0669fae#.nlqjctxl3

The Animated library is designed to make it very easy to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

  1. Всякие левые библиотеки, которые манипулируют DOM через обычный JS или что-то мутят с CSS

react-motion A spring that solves your animation problems. https://github.com/chenglou/react-motion больше демо https://github.com/chenglou/react-motion/wiki/Gallery-of-third-party-React-Motion-demos

react-flip-move Effortless animation between DOM changes (eg. list reordering) using the FLIP technique. https://github.com/joshwcomeau/react-flip-move

  1. Анимация произвольных свойств средствами реакта

react.animate state animation plugin for react.js https://github.com/pleasetrythisathome/react.animate

React.Animate is a different approach to animate based on state rather than direct DOM mutation using $.animate or similar. While it's great that you can use refs to get DOM nodes after render, the biggest benefit to using react is that there is always a direct, observable, and testable relationship between component props, state, and the rendered output. Mutating the dom directly is an antipattern. What we really want to animate is not the DOM, it's component state.

На мой вкус этот способ логичный и предпочтительный. В примере можно анимировать одно свойство за один раз это как раз синтаксис для нескольких свойств, их можно добавлять через запятую

  randomSize: function() {
    this.animate({
      width: _.random(20, 300)
    }, 500, function() {
      console.log("random size reached!");
    });
  }

а нам нужно как минимум тянуть 2 координаты

но по синтаксису есть два варианта, этот похож на анимацию любого количества свойств за присест:

this.animate(properties [, duration ] [, easing ] [, complete ] );

это для одного

this.animate(key, value [, duration ] [, easing ] [, complete ] );

Здесь анимация в андроиде: https://github.com/1i7/rraptor/blob/master/RraptorPult/src/com/rraptor/pult/view/PlotterAreaView.java#L52

sadr0b0t commented 7 years ago

Для коллекции - бенчмарк анимации для разных фреймворков

Animating 2048 SVG nodes in React, Preact, Inferno, Vue, Angular 2, and CycleJS – a side-by-side comparison https://swizec.com/blog/animating-svg-nodes-react-preact-inferno-vue/swizec/7311

sadr0b0t commented 7 years ago

Заработало react.animate после пляски

Пришлось обновить код модуля из npm до последнией версии из репозитория и додумать, как правильно импортировать модуль в файле компонента. Написал багрепорт, если не зальет новую версию в npm, придется сделать форк и залить дубль модуля.

Вообще, проект полудохлый, последний коммит 2 года назад. Но по философии и по синтаксису он пока самый правильный - анимацию для любого элемента (через состояния) делает одна строка чистого ява-скрипта по событию, в разметку компонента не нужно добавлять никаких левых тегов и не нужно рисовать какие-то левые стили CSS.

https://github.com/pleasetrythisathome/react.animate/issues/20 ok, I was able to make it work in the following way:

  1. Installed react.animate from npm

    npm install react.animate --save
  2. Manually updated local node_modules/react.animate/react.animate.js with latest code from github

  3. Installed ease-component (npm did not take it as react.animate dep by some reason)

    npm install ease-component --save
  4. Added require('react.animate') call to the top of the component module

var React = require('react');
require('react.animate');
...
var MyComponent = React.createClass({
    mixins: [React.Animate],
  1. this.animate did work for me after that
    this.animate({posX: pos.x, posY: pos.y, posZ: pos.z}, 500);