views:

1324

answers:

2

What I'd like to do is draw my graphics on a buffer and then be able to copy it as is to the canvas so I can do animation and avoid flickering. But I couldn't find this option. Anyone know how I can go about this?

A: 

Rather than rolling your own, you're probably going to get the best mileage by using an existing library for creating clean and flicker-free JavaScript animation:

Here's a popular one: http://processingjs.org

AndrewDotHay
Exactly! Why bother and write 10 lines of your own code, when you can just use a whole 275KB library without having the slightest clue about it!? Yes, I was being sarcastic.
Tom
+3  A: 

A very simple method is to have two canvas-elements at the same screen location and set visibility for the buffer that you need to show. Draw on the hidden and flip when you are done.

Some code:

CSS:

canvas { border: 2px solid #000; position:absolute; top:0;left:0; 
visibility: hidden; }

Flipping in JS:

Buffers[1-DrawingBuffer].style.visibility='hidden';
Buffers[DrawingBuffer].style.visibility='visible';

DrawingBuffer=1-DrawingBuffer;

In this code the array 'Buffers[]' holds both canvas-objects. So when you want to start drawing you still need to get the context:

Canvas= Buffers[DrawingBuffer].getContext('2d');
Fedor van Eldijk