sAs59
sAs59

Reputation: 572

Aligning an element with background-size:cover

I'm trying to implement the following code in React JS. But, it behaves differently when resizing window. Any ideas?

function updatePointer() {
var windowWidth = $(window).width();
var windowHeight = $(window).height();

// Get largest dimension increase
var xScale = windowWidth / image.width;
var yScale = windowHeight / image.height;
var scale;
var yOffset = 0;
var xOffset = 0;

if (xScale > yScale) {
    // The image fits perfectly in x axis, stretched in y
    scale = xScale;
    yOffset = (windowHeight - (image.height * scale)) / 2;
} else {
    // The image fits perfectly in y axis, stretched in x
    scale = yScale;
    xOffset = (windowWidth - (image.width * scale)) / 2;
}

pointer.css('top', (target.y) * scale + yOffset);
pointer.css('left', (target.x) * scale + xOffset);

}

Fiddle code: http://jsfiddle.net/Tyriar/ypb5P/1/

Here is my code: Edit Map pointers

Upvotes: 1

Views: 60

Answers (1)

duwalanise
duwalanise

Reputation: 1302

In your normal code target is always constant but in your react code this.state.left and this.state.top changes constantly try adding target in react as well.

this.state = {
  target: { x: 184, y: 88 },
  left: 500,
  top: 550,
};

and use it in setState

this.setState({
  left: (this.state.target.x * scale) + xOffset,
  top: (this.state.target.y * scale) + yOffset,
});

it will then behave in similar way.

Upvotes: 1

Related Questions