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.