user2856111
user2856111

Reputation: 205

animating custom shapes in html5 canvas

I'm new to canvas in html5 and would like to know how to animate a custom shape with lots of coordinates. I searched the web but with n o results. I'm only seeing results for circles or squares.

Here's an example of a random drawing. I would like it to move around the screen without setting coordinates for each point. http://jsfiddle.net/ZJdus/

var drawing = function(){
// rand drawing drawing
  context.strokeStyle = "red";
    context.beginPath();
    context.moveTo(318, 200);
    context.lineTo(183, 87);
    context.lineTo(446, 125);
    context.lineTo(446, 202);
    context.lineTo(383, 236);
    context.lineTo(318, 202);
    context.lineTo(318, 125);
    context.lineTo(446, 125);
    context.lineTo(183, 236);
    context.lineTo(318, 125);
    context.lineTo(383, 187);
    context.lineTo(383, 125);
    context.lineTo(613, 180);
    context.lineTo(446,400);
    context.lineTo(413, 180);
    context.lineTo(350, 180);
    context.lineTo(318, 202);
    context.lineTo(350, 180);
    context.lineTo(183, 125);
    context.stroke();

};

Is there a way to achieve this?

I'm also fairly new to Javascript so please explain as much as possible if you can.

Thanks

Upvotes: 2

Views: 1403

Answers (2)

Zach Babb
Zach Babb

Reputation: 668

If your shape doesn't change, you should absolutely not redraw it every frame. Instead draw the shape once to a buffer canvas and then use drawImage at the location to animate the shape.

var drawing = //same as your code above only context is a buffer canvas...

contextOfDisplayedCanvas.drawImage(canvasWithShape, shape.x, shape.y);

Let me know if that doesn't make sense and I can expand.

Upvotes: 0

user1693593
user1693593

Reputation:

You can use translate() before you redraw the shape:

/// clear canvas before each redraw
context.clearRect(0, 0, context.canvas.width, context.canvas.height);

/// translate canvas (move origin)
context.translate(deltaX, deltaY);

... draw points here...

/// reset translate (faster than save()/restore())
context.translate(-deltaX, -deltaY);

Modified fiddle here

Optionally, instead of resetting the translate just use it as delta values directly instead of the absolute delta as now.

You can also add the delta values directly on your coordinates but that is slower than using the translate approach. Hope this helps.

Upvotes: 1

Related Questions