好的,所以我是KineticJS的新手,在玩它时,我似乎无法将图像背景与图像上方的矩形相结合。现在,如果我删除背景图像,则显示矩形。即使我将矩形代码放在图像上方,仍然不会显示在顶部。当然这是我想要的简单但我似乎无法弄清楚它是什么,并且在stackoverflow上找不到类似的问题。谢谢你的帮助。
这是我的代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.4.min.js"></script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 600,
height: 450
});
//Layer for our background
var background_layer = new Kinetic.Layer();
//Canvas background image
var canvasBackgroundImage = new Image();
canvasBackgroundImage.onload = function() {
var backgroundImage = new Kinetic.Image({
x: 0,
y: 0,
image: canvasBackgroundImage,
width: 600,
height: 450
});
background_layer.add(backgroundImage);
stage.add(background_layer);
};
canvasBackgroundImage.src = 'images/quiz_back.jpg'; //Location of our background
//Question container
var question_container_layer = new Kinetic.Layer();
var question_container = new Kinetic.Rect({
x: 100,
y: 100,
width: 200,
height: 200,
fill: 'green',
stroke: 'black',
strokeWidth: 2
});
question_container_layer.add(question_container);
stage.add(question_container_layer);
</script>
</body>
答案 0 :(得分:2)
您的问题是您要将background_layer
添加到canvasBackgroundImage.onload
功能中的舞台。 Javascript将贯穿整个脚本,并首先将question_container_layer
添加到舞台,然后当您的图片加载时,background_layer
将添加到舞台中。因此,背景图像始终显示在矩形图层的顶部。
要解决此问题,请在onload
功能之外的舞台上添加图层:
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 600,
height: 450
});
//Layer for our background
var background_layer = new Kinetic.Layer();
var question_container_layer = new Kinetic.Layer();
stage.add(background_layer);
stage.add(question_container_layer);
//Canvas background image
var canvasBackgroundImage = new Image();
canvasBackgroundImage.onload = function() {
var backgroundImage = new Kinetic.Image({
x: 0,
y: 0,
image: canvasBackgroundImage,
width: 600,
height: 450
});
background_layer.add(backgroundImage);
background_layer.draw();
};
canvasBackgroundImage.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Location of our background
//Question container
var question_container = new Kinetic.Rect({
x: 50,
y: 50,
width: 200,
height: 200,
fill: 'green',
stroke: 'black',
strokeWidth: 2
});
question_container_layer.add(question_container);
question_container_layer.draw();
</script>
为了在将来避免这种情况,除非您要将动态图层添加到舞台中,否则我建议您在执行任何其他操作之前将所有已知图层添加到舞台。这样您就可以控制图层的顺序。
或者,您也可以使用zIndex
属性来订购图层。见这里:Kinetic.Container#setZIndex