gpt4 book ai didi

javascript - 在 Canvas 上绘图时,滚动有 1/10 的几率导致页面滞后

转载 作者:行者123 更新时间:2023-11-29 17:55:28 25 4
gpt4 key购买 nike

我发现有时当我使用滚轮时,我的 Canvas 会停止绘制。我试图禁用滚动,但问题仍然存在。

这是延迟的示例:https://gyazo.com/8cc175a09ac3961ad59ebb46dca24d48

代码如下:

        var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = getWidth();
c.height = getHeight();

var iconNames = ['android', 'github', 'google-plus', 'instagram', 'linkedin', 'pinterest', 'reddit', 'skype', 'snapchat', 'soundcloud', 'tumblr', 'twitter', 'vimeo', 'youtube'];
var iconsDropped = 0, max = 7;
var drops = [];

for (var i = 0; i < iconNames.length; i++) {
var image = new Image();
image.src = "images/landing/" + iconNames[i] + ".png";
}

pickRandom();
function pickRandom() {
var wait = Math.floor(Math.random() * 2500);
setTimeout(pickRandom, wait);

if (iconNames.length < 1 || iconsDropped >= max) {
return;
}

var img = new Image();
var index = Math.floor(Math.random() * iconNames.length);
var name = iconNames[index];
iconNames.splice(index, 1);

img.onload = function () {
drops.push({
image: img,
width: Math.floor(Math.random() * getWidth()),
height: -50,
name: name,
speed: Math.random() + .5,
cycle: 0
});

iconsDropped++;
};

img.src = "images/landing/" + name + ".png";
}

function draw() {
c.width = getWidth();
c.height = getHeight() - c.offsetTop;
clearCanvas();

for (var i = 0; i < drops.length; i++) {
var drop = drops[i];
drop.height = drop.height + drop.speed;

if (drop.height > getHeight() - c.offsetTop) {
drop.cycle++;

if (drop.cycle == 3) {
var name = drop.name;
drops.splice(i, 1);
iconNames.push(name);
iconsDropped--;
i--;
continue;
} else {
drop.height = -50;
drop.width = Math.floor(Math.random() * getWidth());
}
}

ctx.drawImage(drop.image, drop.width, drop.height, 50, 50);
}

console.log("ASD")
}
setInterval(draw, 2);

function clearCanvas() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.beginPath();
}

最佳答案

做自定义动画时,你应该使用requestAnimationFrame而不是 setIntervalsetTimeout。这是为了让浏览器知道您正在尝试制作动画,并且能够在滚动、背景中的窗口等方面迎合这一点。

根据文档:

You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation. The callback rate may be reduced to a lower rate when running in background tabs or in hidden s in order to improve performance and battery life.

关于javascript - 在 Canvas 上绘图时,滚动有 1/10 的几率导致页面滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501005/

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