处理 HTML5 画布中的大图像

jol*_*eye 5 javascript canvas image html5-canvas

我有一个 15000x15000 像素的矢量图像,我想将其用作画布项目的背景。我需要能够快速且频繁地剪切图像的一部分并将其绘制为背景(在 内requestAnimationFrame)。

为了绘制我正在使用的图像所需的部分......

const xOffset = (pos.x - (canvas.width / 2)) + config.bgOffset + config.arenaRadius;
const yOffset = (pos.y - (canvas.height / 2)) + config.bgOffset + config.arenaRadius;
c.drawImage(image, xOffset, yOffset, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
Run Code Online (Sandbox Code Playgroud)

计算所需背景的面积并绘制图像。这一切都很好,但重绘很慢,第一次绘制甚至更慢。

加载这个巨大的图像似乎很荒谬,而且性能也很缓慢。如何减小文件大小或提高性能?

编辑:没有合理的解决方案来以全尺寸绘制如此大的图像。因为背景是重复图案,所以我当前的解决方案是采用一个图案“单元格”并多次绘制它。

Kai*_*ido 2

15000px x 15000px确实很大。

GPU 必须将其作为原始 RGB 数据存储在内存中(我不记得确切的数学,但我认为它类似于宽度 x 高度 x 3 字节,即您的情况下为 675MB,这比大多数常见 GPU 可以存储的数据要多)处理)。
再加上您可能拥有的所有其他图形,您的 GPU 将被迫放弃大图像并在每一帧中再次抓取它。

为了避免这种情况,您可能最好将大图像分割成多个较小的图像,并每帧调用多次drawImage。这样,在最坏的情况下,GPU 只需要获取所需的部分,而在最好的情况下,它已经将其存储在内存中。

这是一个粗略的概念证明,它将把 5000*5000px 的 svg 图像分割成 250*250px 的图块。当然,您必须根据您的需要对其进行调整,但它可能会给您一个想法。

console.log('generating image...');
var bigImg = new Image();
bigImg.src = URL.createObjectURL(generateBigImage(5000, 5000));
bigImg.onload = init;

function splitBigImage(img, maxSize) {
  if (!maxSize || typeof maxSize !== 'number') maxSize = 500;

  var iw = img.naturalWidth,
    ih = img.naturalHeight,
    tw = Math.min(maxSize, iw),
    th = Math.min(maxSize, ih),
    tileCols = Math.ceil(iw / tw), // how many columns we'll have
    tileRows = Math.ceil(ih / th), // how many rows we'll have
    tiles = [],
    r, c, canvas;

  // draw every part of our image once on different canvases
  for (r = 0; r < tileRows; r++) {
    for (c = 0; c < tileCols; c++) {
      canvas = document.createElement('canvas');
      // add a 1px margin all around for antialiasing when drawing at non integer
      canvas.width = tw + 2;
      canvas.height = th + 2;
      canvas.getContext('2d')
        .drawImage(img,
          (c * tw | 0) - 1, // compensate the 1px margin
          (r * tw | 0) - 1,
          iw, ih, 0, 0, iw, ih);
      tiles.push(canvas);
    }
  }

  return {
    width: iw,
    height: ih,
    // the drawing function, takes the output context and x,y positions
    draw: function drawBackground(ctx, x, y) {
      var cw = ctx.canvas.width,
        ch = ctx.canvas.height;
      // get our visible rectangle as rows and columns indexes
      var firstRowIndex = Math.max(Math.floor((y - th) / th), 0),
        lastRowIndex = Math.min(Math.ceil((ch + y) / th), tileRows),
        firstColIndex = Math.max(Math.floor((x - tw) / tw), 0),
        lastColIndex = Math.min(Math.ceil((cw + x) / tw), tileCols);

      var col, row;
      // loop through visible tiles and draw them
      for (row = firstRowIndex; row < lastRowIndex; row++) {
        for (col = firstColIndex; col < lastColIndex; col++) {
          ctx.drawImage(
            tiles[row * tileCols + col], // which part
            col * tw - x - 1, // x position
            row * th - y - 1 // y position
          );
        }
      }
    }
  };
}

function init() {
  console.log('image loaded');

  var bg = splitBigImage(bigImg, 250); // image_source, maxSize
  var ctx = document.getElementById('canvas').getContext('2d');
  var dx = 1,
    dy = 1,
    x = 150,
    y = 150;
  anim();
  setInterval(changeDirection, 2000);

  function anim() {
    // just to make the background position move...
    x += dx;
    y += dy;
    if (x < 0) {
      dx *= -1;
      x = 1;
    }
    if (x > bg.width - ctx.canvas.width) {
      dx *= -1;
      x = bg.width - ctx.canvas.width - 1;
    }
    if (y < 0) {
      dy *= -1;
      y = 1;
    }
    if (y > bg.height - ctx.canvas.height) {
      dy *= -1;
      y = bg.height - ctx.canvas.height - 1;
    }
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    if(chck.checked) {
      // that's how you call it
      bg.draw(ctx, x, y);
    }
    else {
      ctx.drawImage(bigImg, -x, -y);
    }
    requestAnimationFrame(anim);
  }

  function changeDirection() {
    dx = (Math.random()) * 5 * Math.sign(dx);
    dy = (Math.random()) * 5 * Math.sign(dy);
  }

  setTimeout(function() { console.clear(); }, 1000);
}
// produces a width * height pseudo-random svg image
function generateBigImage(width, height) {
  var str = '<svg width="' + width + '" height="' + height + '" xmlns="http://www.w3.org/2000/svg">',
    x, y;
  for (y = 0; y < height / 20; y++)
    for (x = 0; x < width / 20; x++)
      str += '<circle ' +
      'cx="' + ((x * 20) + 10) + '" ' +
      'cy="' + ((y * 20) + 10) + '" ' +
      'r="15" ' +
      'fill="hsl(' + (width * height / ((y * x) + width)) + 'deg, ' + (((width + height) / (x + y)) + 35) + '%, 50%)" ' +
      '/>';
  str += '</svg>';
  return new Blob([str], {
    type: 'image/svg+xml'
  });
}
Run Code Online (Sandbox Code Playgroud)
<label>draw split <input type="checkbox" id="chck" checked></label>
<canvas id="canvas" width="800" height="800"></canvas>
Run Code Online (Sandbox Code Playgroud)

实际上,在您的具体情况下,我个人甚至会将分割图像存储在服务器上(无论是在 svg 中,因为它应该占用更少的带宽),并从不同的来源生成图块。但我会把它作为练习留给读者。