Search code examples
konva

How to draw customer animations use Konva tweens?


like this bounce and this lightspeed

im already use move ,rotate,fade,scale,etc, code like this

const { x, y } = moveXY;
const tween = creatTween({
  node: kvNode,
  x: x,
  y: y,
  duration: config.enter_duration / 1000, 
  easing: Konva.Easings[config.enter_easings], 
  yoyo: false, 
  onUpdate: function () {},
  onFinish: function () {
    if (!config.enter_direction) {
      tween.reset();
    }
  },
});
tween.play();

How can I achieve animation like above picture


Solution

  • You could achieve it like that. Adjust the steps & values to receive the desired result:

    var width = window.innerWidth;
    var height = window.innerHeight;
    
    const promisedTo = (shape, opts) => {
      return new Promise((res) => shape.to({ onFinish: res, ...opts }));
    };
    
    const sequentialAnimations = async (shape, defaultConfig, configs) => {
      for (let config of configs) {
        await promisedTo(shape, {
          ...defaultConfig,
          ...config,
          onUpdate: () => stage.batchDraw(),
        });
      }
    };
    
    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height,
    });
    
    var layer = new Konva.Layer();
    
    var rect = new Konva.Rect({
      x: 100,
      y: 100,
      width: 50,
      height: 50,
      offsetX: 25,
      offsetY: 25,
      fill: 'green',
    });
    
    var rect2 = new Konva.Rect({
      x: 100,
      y: 200,
      width: 50,
      height: 50,
      offsetX: 25,
      offsetY: 25,
      fill: 'blue',
    });
    
    const bounce = (shape) => {
      const initialState = {
        scaleX: shape.scaleX(),
        scaleY: shape.scaleY(),
        opacity: shape.opacity(),
      };
      sequentialAnimations(shape, { easing: Konva.Easings.EaseInOut }, [
        { scaleX: 0.7, scaleY: 0.7, duration: 0.2 },
        { scaleX: 1, scaleY: 1, duration: 0.2 },
        { opacity: 0, scaleX: 0.2, scaleY: 0.2, duration: 0.4 },
        { ...initialState, duration: 0.3 },
      ]);
    };
    
    const lightspeed = (shape) => {
      const initialState = {
        x: shape.x(),
        skewX: shape.skewX(),
        opacity: shape.opacity(),
      };
      sequentialAnimations(shape, { easing: Konva.Easings.EaseInOut }, [
        { skewX: -1, x: initialState.x - 100, opacity: 0, duration: 0.2 },
        { skewX: -2, x: -50, opacity: 0, duration: 0.4 },
        { ...initialState, duration: 0.3 },
      ]);
    };
    
    layer.add(rect, rect2);
    
    stage.add(layer);
    stage.batchDraw();
    
    lightspeed(rect);
    bounce(rect2);
    <script src="https://unpkg.com/konva@8/konva.min.js"></script>
    <div id="container" />