简体   繁体   中英

How to optimize JS canvas drawing?

My impl of fillRect much (> 3 times) slower than context2d.fillRect. How I can optimize my code or why builtin fillRect faster (some app acceleration?)?

My impl:

  __fillRect : function (data, x, y)//, r, g, b)
  {
    var w = this.__width * 4;
    var idx = x * 4+ y * w;
    var idx_1 = idx + 4;
    var idx_2 = idx + 8;
    var idx_3 = idx + w;
    var idx_4 = idx_3 + 4;
    var idx_5 = idx_3 + 8;
    var idx_6 = idx_3 + w;
    var idx_7 = idx_6 + 4;
    var idx_8 = idx_6 + 8;

    function __setPixelIdx (idx)
    {
      data[idx + 0] = 200;
      data[idx + 1] = 0;
      data[idx + 2] = 0;
      data[idx + 3] = 255;
    }

    __setPixelIdx (idx);
    __setPixelIdx (idx_1);
    __setPixelIdx (idx_2);
    __setPixelIdx (idx_3);
    __setPixelIdx (idx_4);
    __setPixelIdx (idx_5);
    __setPixelIdx (idx_6);
    __setPixelIdx (idx_7);
    __setPixelIdx (idx_8);

  },

Your implementation is slower for a few reasons:

  • You are writing to an array and then copying and converting that into the canvas framebuffer.
  • context2d.fillRect is running native code, not interpreted or JIT compiled JavaScript.
  • context2d can potentially use graphics hardware to draw
  • You are writing single bytes at a time whereas even an unaccelerated native library could write whole int32 pixel values

My advice is use the native fillRect method unless you have a very good reason not too (eg doing your own shading or masking). You will not get anywhere near the speed of the library function.

Calling __setPixelIdx instead of doing the data accessing in the main __fillRect function probably isn't helping much.

Why you write a function that exists in native code? It is obvious that you can't compete with it in terms of speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM