问题:我怎样才能使putImageData()
随着图像各个部分的计算,实时更新画布?
我正在开发一个 JavaScript/TypeScript 应用程序来在 HTML5 上绘制 Mandelbrot 集<canvas>
元素。抛开数学和细节不谈,我的应用程序绘制的集合很好。但是,如果您熟悉可视化该集合,您就会知道绘制可能需要很长时间。
它将在几秒钟内绘制,但在此之前,画布完全空白,然后图像就会出现。我正在寻找一种方法来绘制每一行,因为它是使用putImageData()
。这是我正在尝试的:
// 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() {
// tried this... does not help
// var handler = function(m: Mandelbrot) {
// m.Context.putImageData(m.ImageData, 0, i)
// };
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)
}
// setTimeout(handler(this), 0); // does not help
this.Context.putImageData(this.ImageData, 0, i); // Draw the row on the canvas?
}
}
不知何故,putImageData()
函数在计算图像中的一行后调用,仅在生成整个图像后才显示图像。
我怎样才能使putImageData()
实时更新画布,因为每一行都已计算?
非工作代码的最新更新:
var handler = function(m: Mandelbrot, i: number) {
for (var j: number = 0; j < m.Size.Width; ++j) {
// math
m.setPixelColor(j, color);
}
m.Context.putImageData(m.ImageData, 0, i);
};
var that: Mandelbrot = this;
for(var i: number = 0; i < this.Size.Height; ++i) {
setTimeout(function() {
handler(that, i)
}, 0);
}
工作代码,感谢 ekuusela:
var handler = function(m: Mandelbrot, i: number) {
return function() {
for (var j: number = 0; j < m.Size.Width; ++j) {
// math
m.setPixelColor(j, color);
}
m.Context.putImageData(m.ImageData, 0, i);
}
};
for(var i: number = 0; i < this.Size.Height; ++i) {
setTimeout(handler(this, i), 0);
}