maxwellito / vivus

JavaScript library to make drawing animation on SVG
MIT License
15.25k stars 1.13k forks source link

Move a pencil while drawing ? #247

Open lauhub opened 1 year ago

lauhub commented 1 year ago

Hello,

Your work is really great, thank you for this !

Would it be possible to move a pencil (or another object) along the edge of the drawing ?

Or is there a callback or a function that could be used to move a specific object from the start to the end of a path, to simulate a moving pencil with some coordinates (e.g. the path's start/end coordinates) ?

The purpose would be to have a hand writing effect while the SVG paths are appearing one by one

maxwellito commented 1 year ago

Hello,

Apologies about the delay.

The library doesn't allow such a thing, but it's something you could hack. The problem is, this can only work on oneByOne animation, otherwise there might be more than one line being drawn at the same time code. The .map property of the Vivus instance will have a list of all the path elments to animate. Let's hook the rendering (trace method) to add your code. Here is an example

const yourAnimation = new Vivus(...);

yourAnimation.traceOriginal = yourAnimation.trace;
yourAnimation.trace = function () {
  this.traceOriginal();
  var path = this.map.filter(x => x.progress !== 0 && x.progress !== 1)[0];

  if (!path) return;

  var length = path.length * path.progress;
  var point = path.el.getPointAtLength(length);

  // Do your magic here
  console.log('The coordinates', point);
}

I tested it on the demo page, it works well

Be aware, the coordinates are relative to the viewbox of the SVG.