Estoy creando un juego 2D html5 usando canvas. Actualmente estoy haciendo el mapa que es muy grande (25000px x 25000px). Ahora estoy tratando de agregar texturas a las formas del mapa.
Aquí está el código:
let snowPattern; let sandPattern; let junglePattern; const jungleTexture = new Image(); jungleTexture.src = "./assets/game/map/jungleTexture.png"; jungleTexture.onload = function() { junglePattern = ctx.createPattern(jungleTexture, "repeat"); }; const snowTexture = new Image(); snowTexture.src = "./assets/game/map/snowTexture.png"; snowTexture.onload = function() { snowPattern = ctx.createPattern(snowTexture, "repeat"); }; const sandTexture = new Image(); sandTexture.src = "./assets/game/map/sandTexture.png"; sandTexture.onload = function() { sandPattern = ctx.createPattern(sandTexture, "repeat"); }; //Function to draw map shapes function animate() { mapX = document.documentElement.clientWidth / 2 - camera.x * zoom; mapY = document.documentElement.clientHeight / 2 - camera.y * zoom; ctx.setTransform(1, 0, 0, 1, mapX, mapY); //Arctic if (document.getElementById("3").checked === true) { ctx.fillStyle = snowPattern; } else { ctx.fillStyle = "#EFF4F6"; } ctx.fillRect(0, 0, 12500 * zoom, 12500 * zoom); //Desert if (document.getElementById("3").checked === true) { ctx.fillStyle = sandPattern; } else { ctx.fillStyle = "#E5C068"; } ctx.fillRect(12499 * zoom, 0 * zoom, 12500 * zoom, 12500 * zoom); //Jungle if (document.getElementById("3").checked === true) { ctx.fillStyle = junglePattern; } else { ctx.fillStyle = "#0F7F2A"; } ctx.fillRect(0, 12500 * zoom, 25000 * zoom, 12500 * zoom); window.requestAnimationFrame(animate); } animate();Entonces, cuando solo pongo colores en el fondo de las formas, funciona perfectamente (144 fps constantes), pero con patrones, mis fps disminuyen a 20.
¿Alguien tiene una idea sobre cómo puedo mejorar las actuaciones?
Está tratando de dibujar un rectángulo masivo y crea una sobrecarga que se espera. Depende del navegador, pero el lienzo tiene algunos límites. Cuando llegue a esos límites, sufrirá un rendimiento o se bloqueará. Puede ver los límites aquí Además, dibujar un rectángulo enorme siempre terminará con un rendimiento deficiente.
Mi sugerencia sería: dibuja un rectángulo más pequeño (probablemente un poco más grande que la pantalla del juego) y muévelo hasta el final del rectángulo y justo antes de que finalice el patrón, muévelo de nuevo.
Finalmente, el problema no venía del tamaño, incluso con un píxel recto de 50px x 50px, el rendimiento era terrible. Debe usar ctx.beginPath(), ctx.rect, ctx.closePath() y ctx.fill() para obtener un rendimiento normal.