Search code examples
resizekineticjsstage

Kineticjs how to centre image on stage and resize depending on browser


I am adding an image to the stage as a background image and a rectangle. How can I ensure that the rectangle is centred on the stage and that the background resizes depending on the browser?

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

Solution

  • First things first,

    You have a slight mistake, unless you intended it to be this way for whatever reason:

    //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.
    

    To autosize the stage just create your stage like so:

     var stage = new Kinetic.Stage({
          container: 'container',
          width: window.innerWidth,  
          height: window.innerHeight
     });
    

    To center an object you have to calculate its width and height compared to the stage, and place it accordingly.

    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
    });
    

    This one was simple because your rectangle is half the width and half the height of the stage.

    A more complex solution, which accounts for varying sizes, is something like this:

        x: (stage.getWidth()/2)-(rect.getWidth()/2) // similar for height
        y: (stage.getHeight()/2)-(rect.getHeight()/2) // similar for height