gpt4 book ai didi

javascript - HTML5 Canvas 随着时间的推移而抖动

转载 作者:行者123 更新时间:2023-12-03 08:13:54 26 4
gpt4 key购买 nike

我正在创建一个可以在屏幕上移动图像的网站。但随着时间的推移,图像会变得紧张。我有一个每秒渲染 Canvas 100 次的循环。例如,如果 Canvas 以 60FPS(示例)开始,它会减慢至大约 20 或 10FPS。我的显卡没有问题。有谁知道如何使用 HTML5 Canvas 保持良好的性能?

    <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>

最佳答案

关于javascript - HTML5 Canvas 随着时间的推移而抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com