Search code examples
canvaspixi.js

Pixijs vs. normal screen performance


I want to paint a pixelmap of 500x500 rectangles (one rectangle has 10x10 pixels) and change the colour of about 200 random rectangles every 10ms. I first used pixijs because it says that they have webgl support. To move and zoom on the canvas I use the panzoom package.

When I create graphic objects or sprite objects with pixijs, it works, but the performance is very poor. Especially moving the whole map is super slow and hangs all the time.

If instead I simply take the 2d context from the canvas and use "fillRect(...)" to paint the rectangles, the performance is not a dream either but much better, or even usable at all.

What is the reason for this and what possibilities are there to get even more speed out of this?


Solution

  • Working on the pixel buffer will be the fastest:

    const ctx = canvas.getContext('2d');
    const imageData = new ImageData(500,500);
    const pixelDataView = new Uint32Array(imageData.data.buffer);
    
    let prev=0;
    function anim(now){
      requestAnimationFrame(anim);
      if(now-prev < 10) return;
      prev=now;
      for (let i=0;i<200;i++){
        const tile = (Math.random()*500*500)|0;
        pixelDataView[tile]=0xFF0000FF;
      }
      ctx.putImageData(imageData,0,0);
    }
    anim(0);
    canvas{
      image-rendering:pixelated;
      width:5000px;
      height:5000px;
    }
    <canvas id="canvas" width="500" height="500"></canvas>