我正在使用HTML5 Canvas和KineticJS构建动画。动画效果很好。但是,我注意到有时在刷新时,我动画的图像的图层顺序会重新排列。这种层次顺序的切换似乎是随机发生的。例如,我可以单击刷新5次,图层顺序很好...再单击刷新3次,图层顺序重新排列。任何人都可以帮助为什么这种层顺序的随机切换发生?
答案 0 :(得分:0)
这是你的问题:
mac3rdpieceImageObj.onload = function () {
// add the kinetic image to the layer
mac3rdpieceLayer.add(mac3rdpiece);
// add the layer to the stage
myAnimateStage.add(mac3rdpieceLayer);
};
mac2ndpieceImageObj.onload = function () {
// add the kinetic image to the layer
mac2ndpieceLayer.add(mac2ndpiece);
// add the layer to the stage
myAnimateStage.add(mac2ndpieceLayer);
};
mac1stpieceImageObj.onload = function () {
// add the kinetic image to the layer
mac1stpieceLayer.add(mac1stpiece);
// add the layer to the stage
myAnimateStage.add(mac1stpieceLayer);
};
如果禁用浏览器缓存,则会更频繁地出现问题。使用这3个onload函数,您无法控制首先加载哪个图像。他们可能会按顺序装载,但有时他们不会。无论加载哪个订单,都会先添加layer
,因此有时它们会出现故障。
如果必须为3张图片使用3个不同的图层,则可以通过在onload
函数的OUTSIDE中添加图层来解决此问题:
myAnimateStage.add(mac3rdpieceLayer); //Add this layer to the stage first,
myAnimateStage.add(mac2ndpieceLayer); //Then this layer.
myAnimateStage.add(mac1stpieceLayer); //Then this layer. This is the top layer because it was added last.
mac3rdpieceImageObj.onload = function () {
mac3rdpieceLayer.add(mac3rdpiece);
mac3rdpieceLayer.draw();
};
mac2ndpieceImageObj.onload = function () {
mac2ndpieceLayer.add(mac2ndpiece);
mac2ndpieceLayer.draw();
};
mac1stpieceImageObj.onload = function () {
mac1stpieceLayer.add(mac1stpiece);
mac1stpieceLayer.draw();
};
保证添加图层的顺序。
您还需要在图像加载后在每个图层上使用draw()
功能,以便您可以在画布上看到图像。这是更新后的jsfiddle
<强>建议:强>
不要为3张图片使用3个图层,而是对每个包含 1张图片的群组使用 1层和3个群组(以及其他任何内容)你需要在每个组内添加)。像这样:
var macLayer = new Kinetic.Layer();
myAnimateStage.add(macLayer);
var mac1stpieceGroup = new Kinetic.Group({
//I suggest moving each image's (x,y) coordinates inside their group
});
var mac2ndpieceGroup = new Kinetic.Group({
//And using x:0, y:0 for the actual image coordinates
});
var mac3rdpieceGroup = new Kinetic.Group({
//That way the group holds the position, and you only have to manage one coordinate per group/image
});
macLayer.add(mac3rdpieceGroup); //Here's the order of your groups
macLayer.add(mac2ndpieceGroup);
macLayer.add(mac1stpieceGroup);
mac3rdpieceImageObj.onload = function () {
mac3rdpieceGroup.add(mac3rdpiece);
macLayer.draw();
};
mac2ndpieceImageObj.onload = function () {
mac2ndpieceGroup.add(mac2ndpiece);
macLayer.draw();
};
mac1stpieceImageObj.onload = function () {
mac1stpieceGroup.add(mac1stpiece);
macLayer.draw();
};
有关详细信息,请参阅此问题:What are the differences between group and layer in KineticJs
最后注意事项:
作为最后一种选择,您还可以使用 zIndex
属性来订购哪一层(或组!)应该出现在其他层之上。 Kinetic.Container#setZIndex