Skip to content Skip to sidebar Skip to footer

Android Significantly Slower In Resizing And Moving Multiple Canvas Elements

I need to build a kind of map in canvas, which must be able to hold more than 10.000 elements and thus has quiet big dimensions in some cases (> 8000px width, >4000 px height

Solution 1:

The real problem you're hitting is you're overloading the GPU. Loading that much data all and once then moving it around is going to put a toll on the GPU and likely force the browser into software rendering mode, which is a big performance hit.

Instead, I'd suggest changing your approach. Rather than having various large canvases, you should have one canvas that is, at most, the size of the users screen. Then, utilize methods of the canvas API such as scale and translate to render what you need. For an added bonus, avoid trying to render things which are off screen.

It may seem like having to redraw the scene every time you move around would be slow but it's not. The reality is that either you specify exactly what needs to be drawn or the browser has to attempt to draw all of it again when you shift it around. Here's a brief example of how you can render and move large images.

var ctx = document.querySelector('canvas').getContext('2d');
var img = newImage();
img.src = 'https://placeimg.com/1000/1000/nature';
img.onload = start;


functionstart() {
  var xDirection = -1;
  var yDirection = -1;
  var xPosition = 0;
  var yPosition = 0;
  
  var prev = Date.now();
  (functionrender() {
    var now = Date.now();
    var delta = (now - prev) / 1000;
    
    xPosition += xDirection * delta * 20;
    yPosition += yDirection * delta * 40;
    if (xPosition > 0) {
      xPosition = 0;
      xDirection *= -1;
    } elseif (xPosition < -320) {
      xPosition = -320;
      xDirection *= -1;
    }
    if (yPosition > 0) {
      yPosition = 0;
      yDirection *= -1;
    } elseif (yPosition < -240) {
      yPosition = -240;
      yDirection *= -1;
    }
    
    prev = now;
    ctx.save();
    ctx.translate(xPosition, yPosition);
    ctx.drawImage(img, 0, 0);
    ctx.restore();
    requestAnimationFrame(render);
  })();
}
body {
  background: #111;
}
canvas {
  background: #FFF;
}
<canvaswidth="320"height="240"></canvas>

Post a Comment for "Android Significantly Slower In Resizing And Moving Multiple Canvas Elements"