我正在尝试使用KineticJS创建一个2D画布动画。 图像作为背景加载到html5画布,我试图水平移动它。 最初代码运行正常。几秒钟后,移动速度降低并开始卡住,最后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;
}
答案 0 :(得分:1)
这是因为你在循环中添加了很多新图层,而.clear()并没有将它们从绘制队列中删除。添加一次这些图像/图层,然后在移动时对它们进行操作等。