提高精灵绘图性能

时间:2018-06-08 02:33:22

标签: javascript performance canvas

我有这个函数来绘制一个精灵对象(它只是一个带有像素值数组的对象):

#include <iostream>
#include <atomic>

class Object
{
public:
    Object()    // Constructor
    {
        // initialize the object
        // ...

        m_objCount++;   // Increase object count when creating object (In constructor)
    }

    Object(const Object& obj)   // Copy constructor
    {
        m_objCount++;
    }

    Object(Object&&) // Move constructor
    {
        m_objCount++;
    }

    ~Object()
    {
        m_objCount--;   // Decrease object count when destroying object
    }

    static int object_count()   // Define a static member function to retrive the count
    {
        return m_objCount;
    }

private:
    static std::atomic_int m_objCount;  // Use static member to store object count, 
                                        // use std::atomic_int to make sure it is thread safe
};

std::atomic_int Object::m_objCount; // Initialize static member

int main()
{
    Object obj;

    // prints "obj count: 1"
    std::cout << "obj count: " << obj.object_count() << std::endl;          // call object_count() with object
    std::cout << "obj count: " << Object::object_count() << std::endl;      // call object_count() with class name
}

唯一缺少的是this.draw = (ctx, x, y, scale) => { let i = 0; let startIndex, red, green, blue, alpha, currentX, currentY; while(i < this.size.width * this.size.height){ startIndex = i * 4; red = this.pixArray[startIndex]; green = this.pixArray[startIndex + 1]; blue = this.pixArray[startIndex + 2]; alpha = this.pixArray[startIndex + 3]; // Draw, but not if the pixel is invisible if(alpha != 0){ ctx.fillStyle = `rgba(${red}, " + ${green} + ", " + ${blue} + ", " + ${alpha / 255.0} + ")`; currentX = i % this.size.width; currentY = (i - currentX) / this.size.width; ctx.fillRect(Math.round(x + (currentX * scale)), Math.round(y + (currentY * scale)), Math.round(scale), Math.round(scale)); } i++; } } ,它是Uint8Array的像素值。

然而,表现相当糟糕。我发现画布更改状态(pixArray)会丢失一些性能,但我必须在每次迭代时修改它。即使fillStyle保持不变,性能仍然是不可接受的。我意识到我有选择或预渲染,但我希望避免这种情况。

1 个答案:

答案 0 :(得分:2)

使用ImageData将数组直接blit到临时画布,然后在一次操作中以适当的比例将其绘制到目标画布:

255 bytes