0

I have a quadratic curve rendered on a canvas. I want to animate it by means of window.setInterval and changing it's dimensions (note not simply changing it's scale) thereafter.

How do I retain an editable reference to the path after calling context.closePath()?

user1561108
  • 2,666
  • 9
  • 44
  • 69
  • 2
    Once you've drawn something on the `canvas` it's pixels, it doesn't retain an object representation. If you want to manipulate objects instead of pixels either use [SVG](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-map-element.html#svg-0) or [use a library](http://kineticjs.com/) – robertc Dec 27 '12 at 18:07
  • so it's not possible to 'redraw' a path already visible on the canvas? Or is there another way like deleting the old one and putting a new one in it's place? – user1561108 Dec 27 '12 at 18:25
  • 2
    No, once drawn it's just pixels. Animation in `canvas` is achieved by clearing pixels and drawing new, slightly different, pixels. – robertc Dec 27 '12 at 18:35
  • 1
    You can clear the canvas and just redraw the path with different parameters. If you have stuff you don't want to clear just put the path on it's own canvas. – hobberwickey Dec 27 '12 at 18:43

1 Answers1

0

I'd recommend that you maintained a reference to the path in a new Path object; that way you could modify x, y, points etc on the fly and then render it each animation step.

var testPath = new Path(100, 100, [[40, 40], [80, 80]]);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

function Path(x, y, points)
{
    this.x = x;
    this.y = y;
    this.points = points;
}

function update()
{
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = 'red';
    ctx.moveTo(testPath.points[0][0], testPath.points[0][1]);
    for (var i = 1; i < testPath.points.length; i++)
    {
        ctx.lineTo(testPath.points[i][0], testPath.points[i][1]);
    }
    ctx.stroke();
    testPath.points[1][1]++; // move down

    // loop
    requestAnimationFrame(update);
}

update();​

For some reason JSFiddle doesn't play nice with Paul Irish's requestAnimationFrame polyfill but it should work locally. I'd definitely recommend this over setInterval.

http://jsfiddle.net/d2sSg/1/

Ben
  • 10,106
  • 3
  • 40
  • 58