简体   繁体   中英

Center a point/div in viewport

We have div with an large image set as background. The background image in most cases will be larger than the div. Hence the div background pans. (refer to Fiddle ).

The image is a floor plan with rooms on it.
Rooms are indicated by some markers with some location (x,y). (not shown in example for now)

<div class="bg-img"></div>

<p>
    <input type="button" value="center on a point" id="center"/>
</p>

div.bg-img {
    background-image: url(http://www.bumc.bu.edu/supportingbusm/files/2012/01/Typical-Floor-Plan.jpg);
    background-position: 0 0;
    background-repeat: no-repeat;
    background-color: blue;
    border: 1px solid #aaa;
    width: 450px;
    height: 450px;
    margin: 25px auto;        
}

Fiddle for the same is here

The code used for moving the div background is @ jQuery - drag div css background

What we want is to center a known point (x,y) within the image in the viewport. (or center the viewpoint around a known point?)

The point (x,y) will be the location of the room. When the user clicks on any of the rooms from the list, the viewport should pan to the location of the room. All the rooms have some pre defined (x,y) position.(Something similar to how google maps centers its map on a marker location) . Also if the room/point is at the edges of the map,bringing it into the viewport will also suffice.

Couldn't figure out how to center the viewport part. Any clue?

Note 1 : In the example below, the user clicks "Room 3" and "Room 3" is panned into the view and centered in the viewport.

Note 2 : Room 3 is not shown exactly at the center of the viewport (assume it is), just for clarity rough pic. Also the room markers are not shown in the example.

如果单击房间3

Fiddle for the same is here

You'll probably want to set the background position x and y coordinates to center.x - point.x and center.y - point.y, respectively. For example, if the background image is 100px wide by 200px tall, then center.x is 50 and center.y is 50. So if you wanted to position the background image so that position (75, 75) is centered, the background image would be position at (-25px, -25px) to pull it up and to the left such that 75px to the right and 75px down is now at 50px to the left and 50px down, relative to the viewport.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM