Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 / js - how to animate straight line between two coordinates?

Tags:

html

jquery

Simple enough question (could be wrong)

im looking to animate between two points in a straight line, using HTML5 and/or Jquery.

ctx.beginPath();
ctx.moveTo(0, 0); // a
ctx.lineTo(100, 100); // b
ctx.stroke();

http://jsbin.com/enobes

EDIT : I ended up developing a library for svg path animation http://lazylinepainter.info/

example

like image 321
Cam Avatar asked Mar 18 '12 22:03

Cam


3 Answers

You could use a linear interpolation or lerp. Something like this. Here is an example on jsfiddle: http://jsfiddle.net/UtmTh/ and here is the main code:

var canvas = $("#paper")[0];
var c = canvas.getContext("2d");

var startX = 50;
var startY = 50;
var endX = 100;
var endY = 100;
var amount = 0;
setInterval(function() {
    amount += 0.05; // change to alter duration
    if (amount > 1) amount = 1;
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.strokeStyle = "black";
    c.moveTo(startX, startY);
    // lerp : a  + (b - a) * f
    c.lineTo(startX + (endX - startX) * amount, 
             startY + (endY - startY) * amount);
    c.stroke();
}, 30);​
like image 58
Zevan Avatar answered Nov 15 '22 22:11

Zevan


You should check this out : http://paulirish.com/2011/requestanimationframe-for-smart-animating/ it is fairly easy to do, after reading it you should be able to do it! There is also an example.

like image 25
Vallières Avatar answered Nov 15 '22 21:11

Vallières


Thanks valli-R and Zevan,

I've coded an amalgam of your two answers which uses lerp with requestAnimFrame

http://jsbin.com/enobes/6

like image 29
Cam Avatar answered Nov 15 '22 22:11

Cam