ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL-2024.02.07 - 이미지에 원 그리기
    > Frontend/JS 2024. 2. 7. 23:28

     

     

    이미지에서 마우스 클릭 이벤트가 발생한 경우, 해당 부위에 원 그리는 함수

     

    // 이미지 위에 사용자 클릭 위치에 마커를 생성하는 함수 정의
    const createClickMarker = (positionX, positionY) => {
      const markerElement = document.createElement("div");
      markerElement.style.position = "absolute";
      markerElement.style.left = `${positionX}px`;
      markerElement.style.top = `${positionY}px`;
      markerElement.style.width = "10px";
      markerElement.style.height = "10px";
      markerElement.style.border = "1px solid white";
      markerElement.style.backgroundColor = "transparent";
      markerElement.style.borderRadius = "50%";
      // 마커를 클릭한 정확한 위치로 조정
      markerElement.style.transform = "translate(-50%, -50%)";
      markerElement.style.boxSizing = "border-box";
      markerElement.classList.add("marker-on-image"); // 마커에 CSS 클래스 추가
      return markerElement;
    };
    
    // 이미지 클릭 이벤트 핸들러
    const handleImageClick = (event) => {
      // div 태그 클릭을 무시하여 마커 클릭 시 이벤트가 발생하지 않도록 함
      if (event.target.tagName.toLowerCase() === "div") return;
    
      // 클릭된 이미지의 위치와 크기 정보를 가져옴
      const imageBounds = event.target.getBoundingClientRect();
      
      // 클릭된 위치를 이미지 내 좌표로 변환
      const clickX = event.clientX - imageBounds.left; 
      const clickY = event.clientY - imageBounds.top;
      
      // 마커 생성 및 위치 설정
      const newMarker = createClickMarker(clickX, clickY);
      
      // 마커가 이미지 위치를 기준으로 배치되도록 설정
      event.target.parentNode.style.position = "relative";
      event.target.parentNode.appendChild(newMarker); // 마커를 이미지 부모 요소에 추가
    
      // 클릭된 위치 데이터를 저장하는 배열에 추가
      selectedPositions.value.push({
        x: clickX,
        y: clickY,
      });
    };

     

     

    문제점과 해결점

    1. 이미지의 크기가 변경되거나  원본 사이즈가 매우 큰 경우 ,  그린 동그라미 좌표가 변경  > 스케일 관리

     

    댓글

Designed by Tistory.