首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 實現圖片以中心點為基準的縮放效果

     編輯:程式設計疑難解答

需求場景

默認情況下,通過修改 img.width 和 img.height 進行縮放時,圖片以左上角為錨點,導致視覺中心偏移。需求是實現以圖片中心為原點的定點縮放。

核心原理

縮放的同時,動態計算並調整圖片的位置屬性,使其中心點座標保持不變:

  • 若圖片 position: absolute 或 relative:調整 left 和 top
  • 若圖片無定位(static):調整 margin-left 和 margin-top

實現代碼

function 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>

進階優化:CSS Transform 方案

現代瀏覽器推薦使用 transform: scale(),性能更優且無需手動計算位置:

imgElement.style.transformOrigin = 'center center';
imgElement.style.transform = `scale(${scale})`;

此方案不影響文檔流佈局,適合大多數場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved