Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
Speeding up canvas image drawing

I'm trying to draw a lot of images in a canvas (like 2000). I want to repeat this operation at least 8-10 times (on different canvases). I have trying to benchmark my code:

const CANVAS_SIZE = 281;

const getRandom = (min, max) => Math.random() * (max - min) + min;

const generateCoordinates = (n) => {
  const coordinates = [];
  for (let i = 0; i < n; i++) {
    const x = getRandom(0, CANVAS_SIZE);
    const y = getRandom(0, CANVAS_SIZE);
    coordinates.push([x, y]);
  }
  return coordinates;
};

const benchmark = (n, draw) => {
  const img = new Image();
  img.src = "svg.svg";
  const coordinates = generateCoordinates(n);
  const canvas = document.querySelector("#canvas");
  const context = canvas.getContext("2d");

  const t0 = performance.now();

  for (let i = 0; i < coordinates.length; i++) {
    const [x, y] = coordinates[i];
    context.drawImage(img, x, y);
  }

  const t1 = performance.now();
  return (t1 - t0) / 1000;
};

But the problem is that even though it returns very few milliseconds, the final image takes a while to load. I do not know why this is happening. I have been reading and it may be the image loading time, but that does not make sense because I'm running that code in local with:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas</title>
</head>

<script src="index.js"></script>

<style>
    .canvas {
        border: 1px solid red;
        margin: auto;
    }

    .canvas-wrapper {
        border: 1px solid green;
        display: flex;
    }
</style>

<body>
    <div class="canvas-wrapper">
        <canvas class="canvas" id="canvas" width="281" height="281"></canvas>
    </div>
</body>

</html>

And the attached svg file. Does anyone know how to speed it up? I have also tried using an offscreen canvas but I have not been able to make it work.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda