gpt4 book ai didi

javascript - 动画性能随着时间的推移而下降

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

我正在尝试使用 KineticJS 创建 2d HTML Canvas 动画。图像已加载到 html5 Canvas 作为背景,并尝试水平移动它。最初,代码运行良好。几秒钟后,移动速度降低并开始卡住,最后 chrome/firefox 将停止响应。

var CanvasXSize = 800;
var CanvasYSize = 600;
var speed = 30; //lower is faster
var scale = 1.05;
var y = -4.5; //vertical offset

var dx = 0.75;
var imgW;
var imgH;
var x = 0;
var clearX;
var clearY;

var tempImage = new Kinetic.Image();

var stage;
var backgroundLayer;
var img;

var initialize = function(){

img = new Image();
img.src = 'movingBack.jpg'; // image of size 3000x600

stage = new Kinetic.Stage({
container: 'container',
width: 800,
height: 600
});

backgroundLayer = new Kinetic.Layer();

img.onload = function() {
imgW = img.width*scale;
imgH = img.height*scale;
if (imgW > CanvasXSize) { x = CanvasXSize-imgW; } // image larger than canvas
if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas
else { clearX = CanvasXSize; }
if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas
else { clearY = CanvasYSize; }
//Set Refresh Rate
return setInterval(draw, speed);
}
}

function draw() {
//Clear Canvas
backgroundLayer.clear(0,0,clearX,clearY);
//If image is <= Canvas Size
if (imgW <= CanvasXSize) {
//reset, start from beginning
if (x > (CanvasXSize)) { x = 0; }
//draw additional image
if (x > (CanvasXSize-imgW))
{
backgroundLayer.add(new Kinetic.Image(
{
x: CanvasXSize+1,
y: y,
image: img,
width: imgW,
height: imgH
}
));
stage.add(backgroundLayer);
}
}
//If image is > Canvas Size
else {
//reset, start from beginning
if (x > (CanvasXSize)) { x = CanvasXSize-imgW; }
//draw additional image
if (x > (CanvasXSize-imgW))
{
backgroundLayer.add(new Kinetic.Image(
{
x: x-imgW+1,
y: y,
image: img,
width: imgW,
height: imgH
}
));
stage.add(backgroundLayer);
}
}
//draw image
backgroundLayer.add(new Kinetic.Image(
{
x: x,
y: y,
image: img,
width: imgW,
height: imgH
}
));
stage.add(backgroundLayer);
//amount to move
x += dx;
}

最佳答案

那是因为您在循环中添加了很多新图层,并且 .clear() 不会将它们从绘制队列中删除。添加这些图像/图层一次,然后在移动等时对它们进行操作。

关于javascript - 动画性能随着时间的推移而下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22324874/

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