Dibujar fotogramas sucesivos en un lienzo HTML5 solo muestra el último fotograma

I have this complicated loop that calculates various still frames of what I want to show in a canvas element. Each time the frame is calculated it gets displayed I call a timer and wait till I clear it and then the next frames is displayed and so on.

    drawing(transform(alone, Box, canvasx.width, canvasx.height), false, "00f", canvasx);
    drawing(transform(Lines, Box, canvasx.width, canvasx.height), false, "ff0000", canvasx);

    var date = new Date();
    var curDate = null;

    do {
        curDate = new Date();
    }
    while (curDate - date < 550);

    if (alone.length > 0) {
        canvasx.width = canvasx.width;
    } 

if i put a break point in var date line and press play each time, every individual frame get displayed but when I let it run through the canvas is empty while it runs and at the end it displays the last frame.

now if i delete the canvasx.width = canvasx.width; I still get the same behavior only obviously at the end i get all frames drawn one on top of the other.

Obviously its not an animation so i cant call drawing in a setinterval.

does anyone has any idea why;

preguntado el 09 de enero de 11 a las 11:01

1 Respuestas

Usted tener usar setTimeout en lugar de tu bucle.

// JavaScript is single thread, and this BLOCKS the re-rendering and display of the canvas
do {
    curDate = new Date();
}
while (curDate - date < 550);

Also I'd rather use context.clearRect (Véase MDC) instead of the resizing, there's no performance difference whatsoever.

Something along these lines should do it:

function drawCanvas() {
    if (alone.length > 0) {
        // clear canvas
    } 
    drawing(transform(alone, Box, canvasx.width, canvasx.height), false, "00f", canvasx);
    drawing(transform(Lines, Box, canvasx.width, canvasx.height), false, "ff0000", canvasx);
    setTimeout(drawCanvas, 550);
}

Never try to emulate sleep in JavaScript you will block the whole Browser from doing anything while you're sleeping.

Respondido el 09 de enero de 11 a las 16:01

the thing is that its a while loop that calculates everytime the new results, I tried to send the results into a function like the one you wrote but obviously in vain since if the while loop wont finish, the canvas doesnt get updates. I came up with a silly solution to show what i wanted but it only works properly on chrome. elasticrash.info/demos/003/index.html since i pop and closing modals - elasticrash

oh I marked it as correct cause I understood what I have to do. - elasticrash

As a side note, I've also seen cases in Safari OS X where just changing the size of the canvas does not fully clear it; clearRect is definitely the better choice. - Phrogz

@Phrogz Good to know, a lot of sites out there recommend using the resetting of the width :/ - Ivo Wetzel

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.