最近手上有一个项目,遇到一个图片放大,然后图片上的设备相对原来的位置不变,因为之前没做过相关的问题,开始没思路,到最后解决问题。
![](https://img.haomeiwen.com/i13691851/3fdf71ded32b0636.png)
我的做法是,开始固定图片的div的宽度和高度,在this.state里定义图片的高度和宽度,当点击放大是,更新state的高度和宽度,图片就会放大,但是绝对定位的设备距离不会改变,相对之前的位置有所偏移,这个时候就要求,点击放大的时候,设备的距离也要同比增长。
new Promise((resolve) => {
const height = parseInt(imgHeight) + 100
const width = parseInt(imgWidth) + 100
this.setState({
imgWidth: `${width}px`,
imgHeight: `${height}px`,
multiple: multiple + 0.2
})
const value = {
oldH: parseInt(imgHeight),
oldW: parseInt(imgWidth),
}
resolve(value)
}).then((res) => {
const H = 100 / res.oldH
const W = 100 / res.oldW
devList.forEach(item => {
if (!item.x || !item.y) {
return
} else {
item.y =(item.y * (1 + H)).toFixed(0)
item.x =(item.x * (1 + W)).toFixed(0)
}
})
this.setState({
devList: devList
})
})
增加的高度比上之前的高度获得增加的百分比,原有的位置乘以对应的比例,注意这个时候增加的有可能是有小数,如果舍弃小数位,放大的次数越多,相对的偏移量就越多,这里我采用了toFixed(0)方法,四舍五入。
图片放大了,当用户想在放大的图片上获取设备的位置时,这个时候我们 应该获取图片没有放大时候的相对位置。代码如下
recursive = (height, width, X, Y) => {
if (height <= 500) {
return { xAxis: X, yAxis: Y };
} else {
let H = 100 / (height - 100)
let W = 100 / (width - 100)
let x = X / (1 + W)
let y = Y / (1 + H)
return this.recursive((height - 100), (width - 100), x, y)
}
}
XY是放大的坐标位置,这里获取放大的坐标位置还需要考虑到页面滚动的问题,这里就不做阐述,注意就好。height,weight是当前放大图片的宽和高。
还有当用户想缩小页面时,和放大一样的思路,一步一步减小比例,代码如下:
new Promise((resolve) => {
const height = parseInt(imgHeight) - 100
const width = parseInt(imgWidth) - 100
this.setState({
imgWidth: `${width}px`,
imgHeight: `${height}px`,
multiple: multiple + 0.2
})
const value = {
oldH: parseInt(imgHeight),
oldW: parseInt(imgWidth),
}
resolve(value)
}).then((res) => {
const H = 100 / res.oldH
const W = 100 / res.oldW
devList.forEach(item => {
if (!item.x || !item.y) {
return
} else {
item.y = (item.y * (1 - H)).toFixed(0)
item.x = (item.x * (1 - W)).toFixed(0)
}
})
this.setState({
devList: devList
})
})
网友评论