dimanche 19 avril 2015

HTML5 Canvas Drawing in Real Time

Question: How can I make putImageData() update the canvas in real time, as various parts of the image have been computed?




I am working on a JavaScript/TypeScript application to draw the Mandelbrot set on an HTML5 <canvas> element. Math and details aside, my application draws the set just fine. However, if you are familiar with visualizing the set, you know that it can take a long time to draw.


It will draw in a few seconds, but until then, the canvas is completely blank, then the image appears. I'm looking for a way to draw each row as it is computed using putImageData(). Here is what I am trying:



// part of the class definition
private Context: CanvasRenderingContext2D;
private ImageData: ImageData;
private Pixels: number[];

constructor() {
var c: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById("can");

this.Context = c.getContext("2d");
this.ImageData = this.Context.createImageData(this.Size.Width, 1);
this.Pixels = this.ImageData.data;
}

public draw() {
for(var i: number = 0; i < this.Size.Height; ++i) { // Loop over each row
for(var j: number = 0; j < this.Size.Width; ++j) { // Calc px. for one row
// all the math to compute the set... (works)

this.setPixelColor(j, color); // sets a color in this.Pixels (works)
}

this.Context.putImageData(this.ImageData, 0, i); // Draw the row on the canvas?
}
}


Somehow, the putImageData() function, which is called after a row in the image has been computed, only shows the image after the entire image has been generated.


How can I make putImageData() update the canvas in real time, as each row has been been computed?


Aucun commentaire:

Enregistrer un commentaire