Kineticjs how to center the image on the stage and resize depending on the browser

I add an image to the scene as a background image and a rectangle. How can I make sure the rectangle is centered on the scene and that the background size varies 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> 
+4
source share
1 answer

Primarily,

You have a small error if you have not decided that this is so for any 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 authorize a scene, simply create the scene as follows:

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

To center an object, you must calculate its width and height compared to the scene 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 }); 

It was simple because your rectangle is half the width and half the height of the scene.

A more complex solution that takes into account different sizes looks something like this:

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

All Articles