Skip to content

Tweening

Manolo Edge edited this page Oct 16, 2023 · 3 revisions

Cardboard can work in conjunction with tween.js in a very simple and seamless way to add tweening.

To be able to use tweens you must import the extension:

import { makeTween, tweenTag, tween } from 'cardboard-js/dist/ext/tween.js';

makeTween(opts)

Creates the tween itself, which can be reused. It accepts a set of options for configuring the tween. Most importantly it lets you perform an action whenever the tween changes value by using the update callback option.

tweenTag(tag: CTag, tween: (tag: CTag) => Tween)

This function will apply the tween to a tag. It receives a function that returns a tween as the second argument as opposed to the tween directly. This is done, to pass the tag that's supposed to be tweened to the update function.

tween

Reference to the whole tween.js library.

Simple Demo

const sizeEnd = { w: 350, h: 350 };
const sizeStart = { w: 0, h: 0 };

const bounceOut = (tag: CTag) =>
  makeTween({
    from: { ...sizeEnd },
    to: { ...sizeStart },
    duration: 300,
    easing: tween.Easing.Quadratic.InOut,
    update: (value) => tag.setStyle({ width: `${value.w}px`, height: `${value.h}px` }),
  });

let box;
init()
  .append((box = div()))
  .clicked((_) => {
    tweenTag(box, bounceOut, () => { /* tween ended */ });
  })

#### Advanced example This example will tween the Box when it's added or removed from the page. The Box also waits for the tween to end before being remove from the page.

const sizeEnd = { w: 350, h: 350 };
const sizeStart = { w: 0, h: 0 };

const bounceOut = (tag: CTag) =>
  makeTween({
    from: { ...sizeEnd },
    to: { ...sizeStart },
    duration: 300,
    easing: tween.Easing.Quadratic.InOut,
    update: (value) =>
      tag.setStyle({ width: `${value.w}px`, height: `${value.h}px` }),
  });

const bounceIn = (tag: CTag) =>
  makeTween({
    from: { ...sizeStart },
    to: { ...sizeEnd },
    duration: 1000,
    easing: tween.Easing.Elastic.InOut,
    update: (value) =>
      tag.setStyle({ width: `${value.w}px`, height: `${value.h}px` }),
  });

const Box = () => {
  return withLifecycle(
    div().setStyle({
      width: `${sizeEnd.w}px`,
      height: `${sizeEnd.h}px`,
      background: '#f3f3f3',
      scale: '.6',
      borderRadius: '8px',
      display: 'inline-block',
    }),
    {
      start(tag) {
        tweenTag(tag, bounceIn);
      },
      beforeRemove(tag) {
        return new Promise((resolve) =>
          tweenTag(tag, bounceOut, () => resolve(true)),
        );
      },
    },
  );
};

let box: CTag;
init()
  .append((box = Box()), br())
  .clicked((_) => {
    if (box.element.parentElement) box.hide();
    else box.show();
  })