4

我正在向舞台添加一个图像作为背景图像和一个矩形。如何确保矩形在舞台上居中并且背景根据浏览器调整大小?

<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>
4

1 回答 1

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
于 2013-03-05T16:44:39.287 回答