我正在使用畫布創建一個 2D html5 游戲。我目前正在制作非常大的地圖(25000 像素 x 25000 像素)。我現在正在嘗試將紋理添加到地圖形狀
這是代碼:
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();
因此,當我只在形狀的背景上添加顏色時,它運行良好(一致 144 fps),但是使用圖案時,我的 fps 會降低到 20。
有沒有人知道我如何提高性能?
uj5u.com熱心網友回復:
您正在嘗試繪制一個巨大的矩形,它會產生預期的開銷。這取決于瀏覽器,但畫布有一些限制。當您達到這些限制時,您將遭受性能或崩潰。您可以在此處查看限制此外,繪制一個巨大的矩形總是會以性能不佳而告終。
我的建議是:繪制一個較小的矩形(可能比您的游戲螢屏大一點)并將其移動到矩形的末端,就在圖案結束之前,再次將其移回。
uj5u.com熱心網友回復:
最后,問題不是來自大小,即使是 50px x 50px 像素矩形,性能也很糟糕。您需要使用 ctx.beginPath()、ctx.rect、ctx.closePath() 和 ctx.fill() 才能獲得正常的性能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337180.html
標籤:javascript 表现 html5-canvas 纹理 2d 游戏