HTML5实时画布

时间:2015-04-19 17:03:07

标签: javascript html5 canvas typescript

问题:如何计算putImageData()实时更新画布,因为计算了图像的各个部分?


我正在使用JavaScript / TypeScript应用程序在HTML5 <canvas>元素上绘制Mandelbrot集。除了数学和细节之外,我的应用程序绘制的设置就好了。但是,如果您熟悉可视化集合,则表示绘制可能需要很长时间。

它将在几秒钟内绘制,但在此之前,画布完全空白,然后出现图像。我正在寻找一种方法来绘制每一行,因为它是使用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);
}

1 个答案:

答案 0 :(得分:3)

尝试将putImageData和单行的计算包装到setTimeout调用以异步执行它(发布接受编辑:请参阅问题中的最终代码,这样做不会起作用i undefined行中的putImageData

public draw() {
    var that = this;
    var drawRow = function() {
            for(var j: number = 0; j < that.Size.Width; ++j) { // Calc px. for one row
                that.setPixelColor(j, color); // sets a color in this.Pixels (works)
            }

            // TODO specify the dirty region in this call
            that.Context.putImageData(that.ImageData, 0, i); // Draw the row on the canvas?
        };
    for(var i: number = 0; i < this.Size.Height; ++i) {    // Loop over each row
        setTimeout(drawRow, 0);
    }
}