How to fix the click position for placement of a dom element in a transformed div

The following code presents the issue, when you click in the gray area a + sign is added to #node-container. Now if you zoom out using your mouse wheel or touch pad and then pan along x or y axis with click and drag and then try to click to place the + the placement is very wrong.

I want to place the + sign exactly at the mouse position

Codepen

let canvas = document.getElementById('canvas');
let nodeContainer = document.getElementById('node-container');
let pz = {
    offset: {
      x: 0.0,
      y: 0.0
    },
    zoom: 1
  };
let isDragging = false;
let c = 0;

// pan and zoom

const updateDom = () => {
  let x = pz.offset.x * pz.zoom +'px';
  let y = pz.offset.y * pz.zoom +'px';
  let z = pz.zoom;
  nodeContainer.style.transform = `translate(${x}, ${y}) scale(${z})`
}

const handleMouseDown = () => {
  isDragging = true;
};

const handleMouseUp = () => {
  isDragging = false;
};

const handleMouseMove = (e) => {
    if (!isDragging) {
      return;
    }

    if (e.buttons !== 1) {
      isDragging = false;

      return;
    }
  
    pz.offset = {
        x: pz.offset.x + e.movementX / pz.zoom,
        y: pz.offset.y + e.movementY / pz.zoom
      };
  
    updateDom();
  
  };

const handleWheel = (e) => {
      e.preventDefault();
      e.stopPropagation();

      if (e.ctrlKey) {
        const speedFactor =
          (e.deltaMode === 1 ? 0.05 : e.deltaMode ? 1 : 0.002) * 10;
        const pinchDelta = -e.deltaY * speedFactor;
        pz.zoom = Math.min(
              1.3,
              Math.max(0.1, pz.zoom * Math.pow(2, pinchDelta))
            )
      }
  
  updateDom();
}

canvas.onwheel = handleWheel;
canvas.onmousedown = handleMouseDown;
canvas.onmouseup = handleMouseUp;
canvas.onmousemove = handleMouseMove;


canvas.addEventListener('click', (e) => {
  let nc = nodeContainer.getBoundingClientRect();
  let pzx = pz.offset.x / pz.zoom;
  let pzy = pz.offset.y / pz.zoom;
  
  let marker = document.createElement('span');
  marker.innerText = '+'
  marker.style.fontSize = '19pt';
  marker.style.position = 'absolute';
  
  let nx = (e.x/pz.zoom) + nc.x;
  let ny = (e.y/pz.zoom) + nc.y;
  
  marker.style.left = nx - pzx + 'px'
  marker.style.top = ny - pzy + 'px'
  
  nodeContainer.appendChild(marker);
  
});
  <script src="https://cdn.tailwindcss.com"></script>
<div class="grid grid-cols-2 divide-x">
  <div id="canvas" class="relative h-screen bg-gray-100">
    <div id="container" class="absolute origin-top-left w-0 h-0 overflow-visible">
      <div id="node-container" class="absolute w-0 h-0 overflow-visible"></div> <!-- end of #node-container -->
    </div> <!-- end of #container -->
  </div> <!-- end of canvas & left col -->
  <div>
  </div> <!-- end of right col -->
</div>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Zoom and Pan</title>
   <script src="https://cdn.tailwindcss.com"></script>
    <style>
    #canvas {
      position: relative;
      overflow: hidden;
    }
    #node-container {
     position: absolute;
      top: 0;
      left: 0;
    }
    .marker {
      position: absolute;
      font-size: 19pt;
    }
  </style>
</head>
<body>
  <div class="grid grid-cols-2 divide-x">
   <div id="canvas" class="relative h-screen bg-gray-100">
      <div id="container" class="absolute origin-top-left w-0 h-0 overflow- 
 visible">
      <div id="node-container" class="absolute w-0 h-0 overflow-visible"> 
 </div>
      </div>
    </div>
    <div></div>
  </div>

 <script>
    let canvas = document.getElementById('canvas');
    let nodeContainer = document.getElementById('node-container');
    let pz = {
      offset: { x: 0, y: 0 },
      zoom: 1
    };
    let isDragging = false;


    const updateDom = () => {
      let x = pz.offset.x * pz.zoom + 'px';
      let y = pz.offset.y * pz.zoom + 'px';
      let z = pz.zoom;
      nodeContainer.style.transform = `translate(${x}, ${y}) scale(${z})`;
    };

    const handleMouseDown = () => {
      isDragging = true;
    };

const handleMouseUp = () => {
  isDragging = false;
};

const handleMouseMove = (e) => {
  if (!isDragging) return;

  pz.offset = {
    x: pz.offset.x + e.movementX / pz.zoom,
    y: pz.offset.y + e.movementY / pz.zoom
  };

  updateDom();
};

const handleWheel = (e) => {
  e.preventDefault();

  if (e.ctrlKey) {
    const speedFactor = (e.deltaMode === 1 ? 0.05 : e.deltaMode ? 1 : 0.002) * 10;
    const pinchDelta = -e.deltaY * speedFactor;
    const zoomFactor = Math.pow(2, pinchDelta);
    pz.zoom = Math.min(1.3, Math.max(0.1, pz.zoom * zoomFactor));

    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    pz.offset.x -= mouseX / pz.zoom * (zoomFactor - 1);
    pz.offset.y -= mouseY / pz.zoom * (zoomFactor - 1);
  }

  updateDom();
};

    canvas.onwheel = handleWheel;
    canvas.onmousedown = handleMouseDown;
    canvas.onmouseup = handleMouseUp;
    canvas.onmousemove = handleMouseMove;


    canvas.addEventListener('click', (e) => {
      const rect = canvas.getBoundingClientRect();
      const mouseX = (e.clientX - rect.left) / pz.zoom - pz.offset.x;
      const mouseY = (e.clientY - rect.top) / pz.zoom - pz.offset.y;

      let marker = document.createElement('span');
      marker.innerText = '+';
       marker.className = 'marker';
      marker.style.left = mouseX + 'px';
     marker.style.top = mouseY + 'px';

      nodeContainer.appendChild(marker);
    });
  </script>
</body>
 </html>

Try this and see if it works

1

In your code you added the nodeContainer’s x and y to your + , you can try removing it. like:

From:

  let nx = (e.x/pz.zoom) + nc.x;
  let ny = (e.y/pz.zoom) + nc.y;

to:

  let nx = (e.x/pz.zoom);
  let ny = (e.y/pz.zoom);

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật