user721856
user721856

Reputation:

Animate along bezierCurveTo or quadraticCurveTo

Is there a built-in way in javascript to animate an object (an image for example) along a path you've drawn using bezierCurveTo or quadraticCurveTo? What I'm trying to do is precisely animate the trajectory and landing spot of a ball if that helps.

Upvotes: 1

Views: 2740

Answers (3)

futuraprime
futuraprime

Reputation: 5568

There is, though browser support is still spotty: you can use dashed lines.

So if you have a draw function:

function draw() {
  ctx.beginPath();
  ctx.moveTo(20,20);
  ctx.quadraticCurveTo(100,100,30,90);
}

you can set up your animation thus:

var start = null;
var duration = 1000;
var length = 150; // I'm guessing here, but you can calculate it

function step(timestamp) {
  if(start === null) { start = timestamp; } 
  canvas.width = canvas.width;
  var progress = Math.min((timestamp - start)/duration,1);
  ctx.setLineDash([0,length,3,0]);
  ctx.lineWidth = 3;
  ctx.lineDashOffset = progress * length;
  draw();
  ctx.stroke();
  if(progress < 1) {
    requestAnimationFrame(step);
  }
}
requestAnimationFrame(step);

You've just got to make sure the initial dash space is longer than your entire line, and then animate the offset along so the single short dash (your 'dot') slides out along your path. You can round it with lineCap. Working demo: http://jsbin.com/UFOTavoX/1

Support for setLineDash and lineDashOffset is not universal. http://www.rgraph.net/blog/2013/january/html5-canvas-dashed-lines.html talks more about it.

Upvotes: 1

vipergtsrz
vipergtsrz

Reputation: 1061

I know this is kind of late, but I think this might be what you're looking for.

Example: http://joelb.me/scrollpath/ Git: https://github.com/JoelBesada/scrollpath

Upvotes: 1

Simon Sarris
Simon Sarris

Reputation: 63802

Is there a built-in way in javascript

No, sorry. Really that's the short answer here. There's not, at least not in canvas.

There is a way to animate along a path in SVG though. In fact you could animate along SVG and capture all of the x,y points as you go to use in Canvas, though that's probably really inefficient.

The other way is to do the math to bisect (split) a bezier curve, which coincidentally gets you the midpoint of that curve. Then bisect the two smaller curves. Do this over and over and eventually you get a list of midpoints that you can use to plot the trajectory of the object you want to animate.

Upvotes: 0

Related Questions