默認情況下,通過修改 img.width 和 img.height 進行縮放時,圖片以左上角為錨點,導致視覺中心偏移。需求是實現以圖片中心為原點的定點縮放。
縮放的同時,動態計算並調整圖片的位置屬性,使其中心點座標保持不變:
position: absolute 或 relative:調整 left 和 topmargin-left 和 margin-topfunction zoomImage(imgElement, scale) {
// 獲取當前尺寸與位置
const rect = imgElement.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
// 計算新尺寸
const newWidth = rect.width * scale;
const newHeight = rect.height * scale;
// 設置新尺寸
imgElement.style.width = newWidth + 'px';
imgElement.style.height = newHeight + 'px';
// 根據定位方式調整位置,保持中心點不變
const style = window.getComputedStyle(imgElement);
if (style.position === 'absolute' || style.position === 'relative') {
imgElement.style.left = (centerX - newWidth / 2) + 'px';
imgElement.style.top = (centerY - newHeight / 2) + 'px';
} else {
imgElement.style.marginLeft = (centerX - newWidth / 2 - rect.left) + 'px';
imgElement.style.marginTop = (centerY - newHeight / 2 - rect.top) + 'px';
}
}
<img id="myImg" src="photo.jpg" style="position: absolute; left: 100px; top: 100px;">
<button onclick="zoomImage(document.getElementById('myImg'), 1.5)">放大 1.5 倍</button>
<button onclick="zoomImage(document.getElementById('myImg'), 0.8)">縮小 0.8 倍</button>
現代瀏覽器推薦使用 transform: scale(),性能更優且無需手動計算位置:
imgElement.style.transformOrigin = 'center center';
imgElement.style.transform = `scale(${scale})`;
此方案不影響文檔流佈局,適合大多數場景。