我将图像作为背景图像和矩形添加到舞台上。如何确保矩形在舞台上居中并且背景根据浏览器调整大小?
<body style="overflow: hidden">
<div id="container" style="width:100%;height:100%;margin:auto;"></div>
<script>
var stage = new Kinetic.Stage({
container: 'container',
width: 1680,
height: 1050
});
var layer = new Kinetic.Layer();
stage.add(layer);
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: stage.getWidth() / 2,
height: stage.getHeight() / 2,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
layer.add(rect);
stage.add(layer);
var imageObj = new Image();
imageObj.onload = function() {
var myBg = new Kinetic.Image({
x: 0,
y: 0,
image: imageObj,
width: 1770,
height: 1200,
opacity: 0
});
layer.add(myBg);
stage.add(layer);
imageObj.src = 'img/bg.png';
</script>
</body>
答案 0 :(得分:5)
首先,
你有一个小错误,除非你出于某种原因打算这样做:
//these lines
layer.add(myBg); // correct
stage.add(layer); // not correct, remove, you already have the layer on the stage, why add it again?
//instead do this:
layer.draw(); // this will just redraw the layer, since you already added the object.
要自动调整舞台,只需创建您的舞台:
var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
要使对象居中,您必须计算与舞台相比的宽度和高度,并相应地放置它。
var rect = new Kinetic.Rect({
x: stage.getWidth()/4,
y: stage.getHeight()/4,
width: stage.getWidth() / 2,
height: stage.getHeight() / 2,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
这个很简单,因为你的矩形是舞台宽度的一半和高度的一半。
一个更复杂的解决方案,它可以解释不同的尺寸,如下所示:
x: (stage.getWidth()/2)-(rect.getWidth()/2) // similar for height
y: (stage.getHeight()/2)-(rect.getHeight()/2) // similar for height