我正在创建一个在屏幕上移动图像的网站。然而,随着时间的推移,图像变得紧张。我有一个循环,每秒渲染画布100次。例如,如果画布以60FPS开始(示例),它将减慢到大约20或10FPS。我的显卡不是问题。有谁知道如何使用HTML5画布保持良好的性能?
<script>
var posX = 0;
var posY = 0;
var velX = 1;
var velY = 1;
var canvas;
var context;
var img;
var imgWidth;
var imgHeight;
window.onload = function() {
canvas = document.getElementById("mainCanvas");
context = canvas.getContext("2d");
context.fillStyle = "rgba(0, 128, 255, 1.0)";
context.fillRect(0, 0, 800, 500);
canvas.addEventListener("click", doMouseDown, false);
img = document.getElementById("hudson");
imgWidth = img.naturalWidth;
imgHeight = img.clientHeight;
startAction(canvas, context, img, imgWidth, imgHeight);
}
function startAction(canvas, context, img, imgWidth, imgHeight) {
context.clearRect(0, 0, 800, 500);
context.fillStyle = "rgba(0, 128, 255, 1.0)";
context.fillRect(0, 0, 800, 500);
context.fillStyle = "rgba(0, 0, 0, 1.0)";
context.font = "20px Courier New";
context.fillText(("X Position: " + posX), 10, 30);
context.fillText(("X Velocity: " + velX), 10, 60);
context.fillText(("Y Position: " + posY), 10, 120)
context.fillText(("Y Velocity: " + velY), 10, 150);
context.rect(690, 10, 100, 40);
context.stroke();
context.fillText(("velX +1"), 700, 35);
context.rect(690, 60, 100, 40);
context.stroke();
context.fillText(("velX -1"), 700, 85);
context.rect(690, 110, 100, 40);
context.stroke();
context.fillText(("velY +1"), 700, 135);
context.rect(690, 160, 100, 40);
context.stroke();
context.fillText(("velY -1"), 700, 185);
context.drawImage(img, posX, posY);
posX += velX;
posY += velY;
if (posX >= (800 - img.naturalWidth)) { velX *= -1; }
if (posX < (0)) { velX *= -1; }
if (posY >= (500 - img.naturalHeight)) { velY *= -1; }
if (posY < (0)) { velY *= -1; }
}
setInterval(function() {
startAction(canvas, context, img);
}, 10);
function doMouseDown(event) {
var locX = event.pageX;
var locY = event.pageY;
if ((locX >= 690) && (locX <= 790) && (locY >= 10) && (locY <= 50)) {
velX++;
}
if ((locX >= 690) && (locX <= 790) && (locY >= 60) && (locY <= 110)) {
velX--;
}
if ((locX >= 690) && (locX <= 790) && (locY >= 110) && (locY <= 170)) {
velX--;
}
}
</script>
答案 0 :(得分:2)
答案 1 :(得分:0)
你是什么意思&#34;一个循环,每秒渲染画布100次&#34;?循环不能引入管理FPS所需的延迟。您需要setTimeout,setInterval或requestAnimationFrame。
如果您使用的是setTimeout或setInterval,我建议您改为使用requestAnimationFrame。它的性能要高得多。它没有完整的浏览器支持,但有一个常用的polyfill。